project
stringclasses 633
values | commit_id
stringlengths 7
81
| target
int64 0
1
| func
stringlengths 5
484k
| cwe
stringclasses 131
values | big_vul_idx
float64 0
189k
⌀ | idx
int64 0
522k
| hash
stringlengths 34
39
| size
float64 1
24k
⌀ | message
stringlengths 0
11.5k
⌀ | dataset
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
ImageMagick
|
a7759f410b773a1dd57b0e1fb28112e1cd8b97bc
| 1 |
MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const double bias,
ExceptionInfo *exception)
{
#define AdaptiveThresholdImageTag "AdaptiveThreshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickSizeType
number_pixels;
ssize_t
y;
/*
Initialize threshold image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
status=SetImageStorageClass(threshold_image,DirectClass,exception);
if (status == MagickFalse)
{
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Threshold image.
*/
status=MagickTrue;
progress=0;
number_pixels=(MagickSizeType) width*height;
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
channel_bias[MaxPixelChannels],
channel_sum[MaxPixelChannels];
register const Quantum
*magick_restrict p,
*magick_restrict pixels;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
center,
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(height/2L),image->columns+width,height,exception);
q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+
GetPixelChannels(image)*(width/2);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
pixels=p;
channel_bias[channel]=0.0;
channel_sum[channel]=0.0;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
channel_bias[channel]+=pixels[i];
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image);
}
pixels+=GetPixelChannels(image)*image->columns;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
mean;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
channel_sum[channel]-=channel_bias[channel];
channel_bias[channel]=0.0;
pixels=p;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias[channel]+=pixels[i];
pixels+=(width-1)*GetPixelChannels(image);
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image)*(image->columns+1);
}
mean=(double) (channel_sum[channel]/number_pixels+bias);
SetPixelChannel(threshold_image,channel,(Quantum) ((double)
p[center+i] <= mean ? 0 : QuantumRange),q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(threshold_image);
}
if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_image->type=image->type;
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
|
CWE-125
| 182,777 | 3,991 |
312905073757981096515948796514440735664
| null | null | null |
linux
|
6994eefb0053799d2e07cd140df6c2ea106c41ee
| 1 |
static void ptrace_link(struct task_struct *child, struct task_struct *new_parent)
{
rcu_read_lock();
__ptrace_link(child, new_parent, __task_cred(new_parent));
rcu_read_unlock();
}
|
CWE-264
| 182,778 | 3,992 |
156288679258947614390570196352460503888
| null | null | null |
oniguruma
|
0f7f61ed1b7b697e283e37bd2d731d0bd57adb55
| 1 |
onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
OnigCompileInfo* ci, OnigErrorInfo* einfo)
{
int r;
UChar *cpat, *cpat_end;
if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;
if (ci->pattern_enc != ci->target_enc) {
r = conv_encoding(ci->pattern_enc, ci->target_enc, pattern, pattern_end,
&cpat, &cpat_end);
if (r != 0) return r;
}
else {
cpat = (UChar* )pattern;
cpat_end = (UChar* )pattern_end;
}
*reg = (regex_t* )xmalloc(sizeof(regex_t));
if (IS_NULL(*reg)) {
r = ONIGERR_MEMORY;
goto err2;
}
r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc,
ci->syntax);
if (r != 0) goto err;
r = onig_compile(*reg, cpat, cpat_end, einfo);
if (r != 0) {
err:
onig_free(*reg);
*reg = NULL;
}
err2:
if (cpat != pattern) xfree(cpat);
return r;
}
|
CWE-416
| 182,785 | 3,998 |
271415581749750405323787582235055856701
| null | null | null |
stb
|
98fdfc6df88b1e34a736d5e126e6c8139c8de1a6
| 1 |
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y]);
}
}
}
|
CWE-20
| 182,786 | 3,999 |
148378993502453457708205845591307380197
| null | null | null |
stb
|
98fdfc6df88b1e34a736d5e126e6c8139c8de1a6
| 1 |
static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
assert(0);
return NULL;
}
|
CWE-20
| 182,787 | 4,000 |
54906354596068523819812822388718547342
| null | null | null |
stb
|
98fdfc6df88b1e34a736d5e126e6c8139c8de1a6
| 1 |
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
assert(pow((float) r+1, dim) > entries);
assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
return r;
}
|
CWE-20
| 182,788 | 4,001 |
246719121438152277246544954801500586588
| null | null | null |
stb
|
98fdfc6df88b1e34a736d5e126e6c8139c8de1a6
| 1 |
static int start_decoder(vorb *f)
{
uint8 header[6], x,y;
int len,i,j,k, max_submaps = 0;
int longest_floorlist=0;
if (!start_page(f)) return FALSE;
if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
if (f->segments[0] != 30) {
if (f->segments[0] == 64 &&
getn(f, header, 6) &&
header[0] == 'f' &&
header[1] == 'i' &&
header[2] == 's' &&
header[3] == 'h' &&
header[4] == 'e' &&
header[5] == 'a' &&
get8(f) == 'd' &&
get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported);
else
return error(f, VORBIS_invalid_first_page);
}
if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
get32(f); // bitrate_maximum
get32(f); // bitrate_nominal
get32(f); // bitrate_minimum
x = get8(f);
{
int log0,log1;
log0 = x & 15;
log1 = x >> 4;
f->blocksize_0 = 1 << log0;
f->blocksize_1 = 1 << log1;
if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
if (log0 > log1) return error(f, VORBIS_invalid_setup);
}
x = get8(f);
if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
if (!start_page(f)) return FALSE;
if (!start_packet(f)) return FALSE;
do {
len = next_segment(f);
skip(f, len);
f->bytes_in_seg = 0;
} while (len);
if (!start_packet(f)) return FALSE;
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (IS_PUSH_MODE(f)) {
if (!is_whole_packet_present(f, TRUE)) {
if (f->error == VORBIS_invalid_stream)
f->error = VORBIS_invalid_setup;
return FALSE;
}
}
#endif
crc32_init(); // always init it, to avoid multithread race conditions
if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
for (i=0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
f->codebook_count = get_bits(f,8) + 1;
f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
for (i=0; i < f->codebook_count; ++i) {
uint32 *values;
int ordered, sorted_count;
int total=0;
uint8 *lengths;
Codebook *c = f->codebooks+i;
CHECK(f);
x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
c->dimensions = (get_bits(f, 8)<<8) + x;
x = get_bits(f, 8);
y = get_bits(f, 8);
c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
ordered = get_bits(f,1);
c->sparse = ordered ? 0 : get_bits(f,1);
if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
if (c->sparse)
lengths = (uint8 *) setup_temp_malloc(f, c->entries);
else
lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (!lengths) return error(f, VORBIS_outofmem);
if (ordered) {
int current_entry = 0;
int current_length = get_bits(f,5) + 1;
while (current_entry < c->entries) {
int limit = c->entries - current_entry;
int n = get_bits(f, ilog(limit));
if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
memset(lengths + current_entry, current_length, n);
current_entry += n;
++current_length;
}
} else {
for (j=0; j < c->entries; ++j) {
int present = c->sparse ? get_bits(f,1) : 1;
if (present) {
lengths[j] = get_bits(f, 5) + 1;
++total;
if (lengths[j] == 32)
return error(f, VORBIS_invalid_setup);
} else {
lengths[j] = NO_CODE;
}
}
}
if (c->sparse && total >= c->entries >> 2) {
if (c->entries > (int) f->setup_temp_memory_required)
f->setup_temp_memory_required = c->entries;
c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
memcpy(c->codeword_lengths, lengths, c->entries);
setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
lengths = c->codeword_lengths;
c->sparse = 0;
}
if (c->sparse) {
sorted_count = total;
} else {
sorted_count = 0;
#ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
for (j=0; j < c->entries; ++j)
if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
++sorted_count;
#endif
}
c->sorted_entries = sorted_count;
values = NULL;
CHECK(f);
if (!c->sparse) {
c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
} else {
unsigned int size;
if (c->sorted_entries) {
c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
if (!values) return error(f, VORBIS_outofmem);
}
size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
if (size > f->setup_temp_memory_required)
f->setup_temp_memory_required = size;
}
if (!compute_codewords(c, lengths, c->entries, values)) {
if (c->sparse) setup_temp_free(f, values, 0);
return error(f, VORBIS_invalid_setup);
}
if (c->sorted_entries) {
c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
++c->sorted_values;
c->sorted_values[-1] = -1;
compute_sorted_huffman(c, lengths, values);
}
if (c->sparse) {
setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
setup_temp_free(f, lengths, c->entries);
c->codewords = NULL;
}
compute_accelerated_huffman(c);
CHECK(f);
c->lookup_type = get_bits(f, 4);
if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
if (c->lookup_type > 0) {
uint16 *mults;
c->minimum_value = float32_unpack(get_bits(f, 32));
c->delta_value = float32_unpack(get_bits(f, 32));
c->value_bits = get_bits(f, 4)+1;
c->sequence_p = get_bits(f,1);
if (c->lookup_type == 1) {
c->lookup_values = lookup1_values(c->entries, c->dimensions);
} else {
c->lookup_values = c->entries * c->dimensions;
}
if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
if (mults == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < (int) c->lookup_values; ++j) {
int q = get_bits(f, c->value_bits);
if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
mults[j] = q;
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int len, sparse = c->sparse;
float last=0;
if (sparse) {
if (c->sorted_entries == 0) goto skip;
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
} else
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
len = sparse ? c->sorted_entries : c->entries;
for (j=0; j < len; ++j) {
unsigned int z = sparse ? c->sorted_values[j] : j;
unsigned int div=1;
for (k=0; k < c->dimensions; ++k) {
int off = (z / div) % c->lookup_values;
float val = mults[off];
val = mults[off]*c->delta_value + c->minimum_value + last;
c->multiplicands[j*c->dimensions + k] = val;
if (c->sequence_p)
last = val;
if (k+1 < c->dimensions) {
if (div > UINT_MAX / (unsigned int) c->lookup_values) {
setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
return error(f, VORBIS_invalid_setup);
}
div *= c->lookup_values;
}
}
}
c->lookup_type = 2;
}
else
#endif
{
float last=0;
CHECK(f);
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
for (j=0; j < (int) c->lookup_values; ++j) {
float val = mults[j] * c->delta_value + c->minimum_value + last;
c->multiplicands[j] = val;
if (c->sequence_p)
last = val;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
skip:;
#endif
setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
CHECK(f);
}
CHECK(f);
}
x = get_bits(f, 6) + 1;
for (i=0; i < x; ++i) {
uint32 z = get_bits(f, 16);
if (z != 0) return error(f, VORBIS_invalid_setup);
}
f->floor_count = get_bits(f, 6)+1;
f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
for (i=0; i < f->floor_count; ++i) {
f->floor_types[i] = get_bits(f, 16);
if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
if (f->floor_types[i] == 0) {
Floor0 *g = &f->floor_config[i].floor0;
g->order = get_bits(f,8);
g->rate = get_bits(f,16);
g->bark_map_size = get_bits(f,16);
g->amplitude_bits = get_bits(f,6);
g->amplitude_offset = get_bits(f,8);
g->number_of_books = get_bits(f,4) + 1;
for (j=0; j < g->number_of_books; ++j)
g->book_list[j] = get_bits(f,8);
return error(f, VORBIS_feature_not_supported);
} else {
stbv__floor_ordering p[31*8+2];
Floor1 *g = &f->floor_config[i].floor1;
int max_class = -1;
g->partitions = get_bits(f, 5);
for (j=0; j < g->partitions; ++j) {
g->partition_class_list[j] = get_bits(f, 4);
if (g->partition_class_list[j] > max_class)
max_class = g->partition_class_list[j];
}
for (j=0; j <= max_class; ++j) {
g->class_dimensions[j] = get_bits(f, 3)+1;
g->class_subclasses[j] = get_bits(f, 2);
if (g->class_subclasses[j]) {
g->class_masterbooks[j] = get_bits(f, 8);
if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
g->subclass_books[j][k] = get_bits(f,8)-1;
if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
}
g->floor1_multiplier = get_bits(f,2)+1;
g->rangebits = get_bits(f,4);
g->Xlist[0] = 0;
g->Xlist[1] = 1 << g->rangebits;
g->values = 2;
for (j=0; j < g->partitions; ++j) {
int c = g->partition_class_list[j];
for (k=0; k < g->class_dimensions[c]; ++k) {
g->Xlist[g->values] = get_bits(f, g->rangebits);
++g->values;
}
}
for (j=0; j < g->values; ++j) {
p[j].x = g->Xlist[j];
p[j].id = j;
}
qsort(p, g->values, sizeof(p[0]), point_compare);
for (j=0; j < g->values; ++j)
g->sorted_order[j] = (uint8) p[j].id;
for (j=2; j < g->values; ++j) {
int low,hi;
neighbors(g->Xlist, j, &low,&hi);
g->neighbors[j][0] = low;
g->neighbors[j][1] = hi;
}
if (g->values > longest_floorlist)
longest_floorlist = g->values;
}
}
f->residue_count = get_bits(f, 6)+1;
f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
for (i=0; i < f->residue_count; ++i) {
uint8 residue_cascade[64];
Residue *r = f->residue_config+i;
f->residue_types[i] = get_bits(f, 16);
if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
r->begin = get_bits(f, 24);
r->end = get_bits(f, 24);
if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
r->part_size = get_bits(f,24)+1;
r->classifications = get_bits(f,6)+1;
r->classbook = get_bits(f,8);
if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
for (j=0; j < r->classifications; ++j) {
uint8 high_bits=0;
uint8 low_bits=get_bits(f,3);
if (get_bits(f,1))
high_bits = get_bits(f,5);
residue_cascade[j] = high_bits*8 + low_bits;
}
r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < r->classifications; ++j) {
for (k=0; k < 8; ++k) {
if (residue_cascade[j] & (1 << k)) {
r->residue_books[j][k] = get_bits(f, 8);
if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
} else {
r->residue_books[j][k] = -1;
}
}
}
r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
if (!r->classdata) return error(f, VORBIS_outofmem);
memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
int classwords = f->codebooks[r->classbook].dimensions;
int temp = j;
r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
for (k=classwords-1; k >= 0; --k) {
r->classdata[j][k] = temp % r->classifications;
temp /= r->classifications;
}
}
}
f->mapping_count = get_bits(f,6)+1;
f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
if (f->mapping == NULL) return error(f, VORBIS_outofmem);
memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
for (i=0; i < f->mapping_count; ++i) {
Mapping *m = f->mapping + i;
int mapping_type = get_bits(f,16);
if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
if (m->chan == NULL) return error(f, VORBIS_outofmem);
if (get_bits(f,1))
m->submaps = get_bits(f,4)+1;
else
m->submaps = 1;
if (m->submaps > max_submaps)
max_submaps = m->submaps;
if (get_bits(f,1)) {
m->coupling_steps = get_bits(f,8)+1;
for (k=0; k < m->coupling_steps; ++k) {
m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
m->chan[k].angle = get_bits(f, ilog(f->channels-1));
if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
}
} else
m->coupling_steps = 0;
if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
if (m->submaps > 1) {
for (j=0; j < f->channels; ++j) {
m->chan[j].mux = get_bits(f, 4);
if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
}
} else
for (j=0; j < f->channels; ++j)
m->chan[j].mux = 0;
for (j=0; j < m->submaps; ++j) {
get_bits(f,8); // discard
m->submap_floor[j] = get_bits(f,8);
m->submap_residue[j] = get_bits(f,8);
if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
}
}
f->mode_count = get_bits(f, 6)+1;
for (i=0; i < f->mode_count; ++i) {
Mode *m = f->mode_config+i;
m->blockflag = get_bits(f,1);
m->windowtype = get_bits(f,16);
m->transformtype = get_bits(f,16);
m->mapping = get_bits(f,8);
if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
}
flush_packet(f);
f->previous_length = 0;
for (i=0; i < f->channels; ++i) {
f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
#endif
}
if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
f->blocksize[0] = f->blocksize_0;
f->blocksize[1] = f->blocksize_1;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (integer_divide_table[1][1]==0)
for (i=0; i < DIVTAB_NUMER; ++i)
for (j=1; j < DIVTAB_DENOM; ++j)
integer_divide_table[i][j] = i / j;
#endif
{
uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
uint32 classify_mem;
int i,max_part_read=0;
for (i=0; i < f->residue_count; ++i) {
Residue *r = f->residue_config + i;
unsigned int actual_size = f->blocksize_1 / 2;
unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size;
unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size;
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
if (part_read > max_part_read)
max_part_read = part_read;
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
#else
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
#endif
f->temp_memory_required = classify_mem;
if (imdct_mem > f->temp_memory_required)
f->temp_memory_required = imdct_mem;
}
f->first_decode = TRUE;
if (f->alloc.alloc_buffer) {
assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
return error(f, VORBIS_outofmem);
}
f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
return TRUE;
}
|
CWE-20
| 182,789 | 4,002 |
252497019343885265750913403473285119139
| null | null | null |
ImageMagick6
|
7d11230060fa9c8f67e53c85224daf6648805c7b
| 1 |
static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define BoundingBox "BoundingBox:"
#define BeginDocument "BeginDocument:"
#define BeginXMPPacket "<?xpacket begin="
#define EndXMPPacket "<?xpacket end="
#define ICCProfile "BeginICCProfile:"
#define CMYKCustomColor "CMYKCustomColor:"
#define CMYKProcessColor "CMYKProcessColor:"
#define DocumentMedia "DocumentMedia:"
#define DocumentCustomColors "DocumentCustomColors:"
#define DocumentProcessColors "DocumentProcessColors:"
#define EndDocument "EndDocument:"
#define HiResBoundingBox "HiResBoundingBox:"
#define ImageData "ImageData:"
#define PageBoundingBox "PageBoundingBox:"
#define LanguageLevel "LanguageLevel:"
#define PageMedia "PageMedia:"
#define Pages "Pages:"
#define PhotoshopProfile "BeginPhotoshop:"
#define PostscriptLevel "!PS-"
#define RenderPostscriptText " Rendering Postscript... "
#define SpotColor "+ "
char
command[MaxTextExtent],
*density,
filename[MaxTextExtent],
geometry[MaxTextExtent],
input_filename[MaxTextExtent],
message[MaxTextExtent],
*options,
postscript_filename[MaxTextExtent];
const char
*option;
const DelegateInfo
*delegate_info;
GeometryInfo
geometry_info;
Image
*image,
*next,
*postscript_image;
ImageInfo
*read_info;
int
c,
file;
MagickBooleanType
cmyk,
fitPage,
skip,
status;
MagickStatusType
flags;
PointInfo
delta,
resolution;
RectangleInfo
page;
register char
*p;
register ssize_t
i;
SegmentInfo
bounds,
hires_bounds;
short int
hex_digits[256];
size_t
length,
priority;
ssize_t
count;
StringInfo
*profile;
unsigned long
columns,
extent,
language_level,
pages,
rows,
scene,
spotcolor;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);
if (status == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
image_info->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize hex values.
*/
(void) memset(hex_digits,0,sizeof(hex_digits));
hex_digits[(int) '0']=0;
hex_digits[(int) '1']=1;
hex_digits[(int) '2']=2;
hex_digits[(int) '3']=3;
hex_digits[(int) '4']=4;
hex_digits[(int) '5']=5;
hex_digits[(int) '6']=6;
hex_digits[(int) '7']=7;
hex_digits[(int) '8']=8;
hex_digits[(int) '9']=9;
hex_digits[(int) 'a']=10;
hex_digits[(int) 'b']=11;
hex_digits[(int) 'c']=12;
hex_digits[(int) 'd']=13;
hex_digits[(int) 'e']=14;
hex_digits[(int) 'f']=15;
hex_digits[(int) 'A']=10;
hex_digits[(int) 'B']=11;
hex_digits[(int) 'C']=12;
hex_digits[(int) 'D']=13;
hex_digits[(int) 'E']=14;
hex_digits[(int) 'F']=15;
/*
Set the page density.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
if (image_info->density != (char *) NULL)
{
flags=ParseGeometry(image_info->density,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
(void) ParseAbsoluteGeometry(PSPageGeometry,&page);
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
resolution.x=image->x_resolution;
resolution.y=image->y_resolution;
page.width=(size_t) ceil((double) (page.width*resolution.x/delta.x)-0.5);
page.height=(size_t) ceil((double) (page.height*resolution.y/delta.y)-0.5);
/*
Determine page geometry from the Postscript bounding box.
*/
(void) memset(&bounds,0,sizeof(bounds));
(void) memset(command,0,sizeof(command));
cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;
(void) memset(&hires_bounds,0,sizeof(hires_bounds));
priority=0;
columns=0;
rows=0;
extent=0;
spotcolor=0;
language_level=1;
skip=MagickFalse;
pages=(~0UL);
p=command;
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
/*
Note document structuring comments.
*/
*p++=(char) c;
if ((strchr("\n\r%",c) == (char *) NULL) &&
((size_t) (p-command) < (MaxTextExtent-1)))
continue;
*p='\0';
p=command;
/*
Skip %%BeginDocument thru %%EndDocument.
*/
if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0)
skip=MagickTrue;
if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0)
skip=MagickFalse;
if (skip != MagickFalse)
continue;
if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0)
{
(void) SetImageProperty(image,"ps:Level",command+4);
if (GlobExpression(command,"*EPSF-*",MagickTrue) != MagickFalse)
pages=1;
}
if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0)
(void) sscanf(command,LanguageLevel " %lu",&language_level);
if (LocaleNCompare(Pages,command,strlen(Pages)) == 0)
(void) sscanf(command,Pages " %lu",&pages);
if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0)
(void) sscanf(command,ImageData " %lu %lu",&columns,&rows);
/*
Is this a CMYK document?
*/
length=strlen(DocumentProcessColors);
if (LocaleNCompare(DocumentProcessColors,command,length) == 0)
{
if ((GlobExpression(command,"*Cyan*",MagickTrue) != MagickFalse) ||
(GlobExpression(command,"*Magenta*",MagickTrue) != MagickFalse) ||
(GlobExpression(command,"*Yellow*",MagickTrue) != MagickFalse))
cmyk=MagickTrue;
}
if (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0)
cmyk=MagickTrue;
if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0)
cmyk=MagickTrue;
length=strlen(DocumentCustomColors);
if ((LocaleNCompare(DocumentCustomColors,command,length) == 0) ||
(LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) ||
(LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0))
{
char
property[MaxTextExtent],
*value;
register char
*p;
/*
Note spot names.
*/
(void) FormatLocaleString(property,MaxTextExtent,"ps:SpotColor-%.20g",
(double) (spotcolor++));
for (p=command; *p != '\0'; p++)
if (isspace((int) (unsigned char) *p) != 0)
break;
value=ConstantString(p);
(void) SubstituteString(&value,"(","");
(void) SubstituteString(&value,")","");
(void) StripString(value);
if (*value != '\0')
(void) SetImageProperty(image,property,value);
value=DestroyString(value);
continue;
}
if (image_info->page != (char *) NULL)
continue;
/*
Note region defined by bounding box.
*/
count=0;
i=0;
if (LocaleNCompare(BoundingBox,command,strlen(BoundingBox)) == 0)
{
count=(ssize_t) sscanf(command,BoundingBox " %lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
i=2;
}
if (LocaleNCompare(DocumentMedia,command,strlen(DocumentMedia)) == 0)
{
count=(ssize_t) sscanf(command,DocumentMedia " %lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
i=1;
}
if (LocaleNCompare(HiResBoundingBox,command,strlen(HiResBoundingBox)) == 0)
{
count=(ssize_t) sscanf(command,HiResBoundingBox " %lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
i=3;
}
if (LocaleNCompare(PageBoundingBox,command,strlen(PageBoundingBox)) == 0)
{
count=(ssize_t) sscanf(command,PageBoundingBox " %lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
i=1;
}
if (LocaleNCompare(PageMedia,command,strlen(PageMedia)) == 0)
{
count=(ssize_t) sscanf(command,PageMedia " %lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
i=1;
}
if ((count != 4) || (i < (ssize_t) priority))
continue;
if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) ||
(fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1)))
if (i == (ssize_t) priority)
continue;
hires_bounds=bounds;
priority=(size_t) i;
}
if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) &&
(fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon))
{
/*
Set Postscript render geometry.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+.15g%+.15g",
hires_bounds.x2-hires_bounds.x1,hires_bounds.y2-hires_bounds.y1,
hires_bounds.x1,hires_bounds.y1);
(void) SetImageProperty(image,"ps:HiResBoundingBox",geometry);
page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)*
resolution.x/delta.x)-0.5);
page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)*
resolution.y/delta.y)-0.5);
}
fitPage=MagickFalse;
option=GetImageOption(image_info,"eps:fit-page");
if (option != (char *) NULL)
{
char
*geometry;
MagickStatusType
flags;
geometry=GetPageGeometry(option);
flags=ParseMetaGeometry(geometry,&page.x,&page.y,&page.width,
&page.height);
if (flags == NoValue)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidGeometry","`%s'",option);
image=DestroyImage(image);
return((Image *) NULL);
}
page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x)
-0.5);
page.height=(size_t) ceil((double) (page.height*image->y_resolution/
delta.y) -0.5);
geometry=DestroyString(geometry);
fitPage=MagickTrue;
}
if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse)
cmyk=MagickFalse;
/*
Create Ghostscript control file.
*/
file=AcquireUniqueFileResource(postscript_filename);
if (file == -1)
{
ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile",
image_info->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) CopyMagickString(command,"/setpagedevice {pop} bind 1 index where {"
"dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\n"
"<</UseCIEColor true>>setpagedevice\n",MaxTextExtent);
count=write(file,command,(unsigned int) strlen(command));
if (image_info->page == (char *) NULL)
{
char
translate_geometry[MaxTextExtent];
(void) FormatLocaleString(translate_geometry,MaxTextExtent,
"%g %g translate\n",-hires_bounds.x1,-hires_bounds.y1);
count=write(file,translate_geometry,(unsigned int)
strlen(translate_geometry));
}
file=close(file)-1;
/*
Render Postscript with the Ghostscript delegate.
*/
if (image_info->monochrome != MagickFalse)
delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception);
else
if (cmyk != MagickFalse)
delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception);
else
delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception);
if (delegate_info == (const DelegateInfo *) NULL)
{
(void) RelinquishUniqueFileResource(postscript_filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
density=AcquireString("");
options=AcquireString("");
(void) FormatLocaleString(density,MaxTextExtent,"%gx%g",resolution.x,
resolution.y);
(void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double)
page.width,(double) page.height);
read_info=CloneImageInfo(image_info);
*read_info->magick='\0';
if (read_info->number_scenes != 0)
{
char
pages[MaxTextExtent];
(void) FormatLocaleString(pages,MaxTextExtent,"-dFirstPage=%.20g "
"-dLastPage=%.20g ",(double) read_info->scene+1,(double)
(read_info->scene+read_info->number_scenes));
(void) ConcatenateMagickString(options,pages,MaxTextExtent);
read_info->number_scenes=0;
if (read_info->scenes != (char *) NULL)
*read_info->scenes='\0';
}
if (*image_info->magick == 'E')
{
option=GetImageOption(image_info,"eps:use-cropbox");
if ((option == (const char *) NULL) ||
(IsStringTrue(option) != MagickFalse))
(void) ConcatenateMagickString(options,"-dEPSCrop ",MaxTextExtent);
if (fitPage != MagickFalse)
(void) ConcatenateMagickString(options,"-dEPSFitPage ",MaxTextExtent);
}
(void) CopyMagickString(filename,read_info->filename,MaxTextExtent);
(void) AcquireUniqueFilename(filename);
(void) RelinquishUniqueFileResource(filename);
(void) ConcatenateMagickString(filename,"%d",MaxTextExtent);
(void) FormatLocaleString(command,MaxTextExtent,
GetDelegateCommands(delegate_info),
read_info->antialias != MagickFalse ? 4 : 1,
read_info->antialias != MagickFalse ? 4 : 1,density,options,filename,
postscript_filename,input_filename);
options=DestroyString(options);
density=DestroyString(density);
*message='\0';
status=InvokePostscriptDelegate(read_info->verbose,command,message,exception);
(void) InterpretImageFilename(image_info,image,filename,1,
read_info->filename);
if ((status == MagickFalse) ||
(IsPostscriptRendered(read_info->filename) == MagickFalse))
{
(void) ConcatenateMagickString(command," -c showpage",MaxTextExtent);
status=InvokePostscriptDelegate(read_info->verbose,command,message,
exception);
}
(void) RelinquishUniqueFileResource(postscript_filename);
(void) RelinquishUniqueFileResource(input_filename);
postscript_image=(Image *) NULL;
if (status == MagickFalse)
for (i=1; ; i++)
{
(void) InterpretImageFilename(image_info,image,filename,(int) i,
read_info->filename);
if (IsPostscriptRendered(read_info->filename) == MagickFalse)
break;
(void) RelinquishUniqueFileResource(read_info->filename);
}
else
for (i=1; ; i++)
{
(void) InterpretImageFilename(image_info,image,filename,(int) i,
read_info->filename);
if (IsPostscriptRendered(read_info->filename) == MagickFalse)
break;
read_info->blob=NULL;
read_info->length=0;
next=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(read_info->filename);
if (next == (Image *) NULL)
break;
AppendImageToList(&postscript_image,next);
}
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
if (postscript_image == (Image *) NULL)
{
if (*message != '\0')
(void) ThrowMagickException(exception,GetMagickModule(),DelegateError,
"PostscriptDelegateFailed","`%s'",message);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (LocaleCompare(postscript_image->magick,"BMP") == 0)
{
Image
*cmyk_image;
cmyk_image=ConsolidateCMYKImages(postscript_image,exception);
if (cmyk_image != (Image *) NULL)
{
postscript_image=DestroyImageList(postscript_image);
postscript_image=cmyk_image;
}
}
(void) SeekBlob(image,0,SEEK_SET);
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
/*
Note document structuring comments.
*/
*p++=(char) c;
if ((strchr("\n\r%",c) == (char *) NULL) &&
((size_t) (p-command) < (MaxTextExtent-1)))
continue;
*p='\0';
p=command;
/*
Skip %%BeginDocument thru %%EndDocument.
*/
if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0)
skip=MagickTrue;
if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0)
skip=MagickFalse;
if (skip != MagickFalse)
continue;
if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0)
{
(void) SetImageProperty(image,"ps:Level",command+4);
if (GlobExpression(command,"*EPSF-*",MagickTrue) != MagickFalse)
pages=1;
}
if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0)
(void) sscanf(command,LanguageLevel " %lu",&language_level);
if (LocaleNCompare(Pages,command,strlen(Pages)) == 0)
(void) sscanf(command,Pages " %lu",&pages);
if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0)
(void) sscanf(command,ImageData " %lu %lu",&columns,&rows);
if (LocaleNCompare(ICCProfile,command,strlen(ICCProfile)) == 0)
{
unsigned char
*datum;
/*
Read ICC profile.
*/
profile=AcquireStringInfo(MaxTextExtent);
datum=GetStringInfoDatum(profile);
for (i=0; (c=ProfileInteger(image,hex_digits)) != EOF; i++)
{
if (i >= (ssize_t) GetStringInfoLength(profile))
{
SetStringInfoLength(profile,(size_t) i << 1);
datum=GetStringInfoDatum(profile);
}
datum[i]=(unsigned char) c;
}
SetStringInfoLength(profile,(size_t) i+1);
(void) SetImageProfile(image,"icc",profile);
profile=DestroyStringInfo(profile);
continue;
}
if (LocaleNCompare(PhotoshopProfile,command,strlen(PhotoshopProfile)) == 0)
{
unsigned char
*p;
/*
Read Photoshop profile.
*/
count=(ssize_t) sscanf(command,PhotoshopProfile " %lu",&extent);
if (count != 1)
continue;
length=extent;
if ((MagickSizeType) length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
profile=BlobToStringInfo((const void *) NULL,length);
if (profile != (StringInfo *) NULL)
{
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) length; i++)
*p++=(unsigned char) ProfileInteger(image,hex_digits);
(void) SetImageProfile(image,"8bim",profile);
profile=DestroyStringInfo(profile);
}
continue;
}
if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0)
{
register size_t
i;
/*
Read XMP profile.
*/
p=command;
profile=StringToStringInfo(command);
for (i=GetStringInfoLength(profile)-1; c != EOF; i++)
{
SetStringInfoLength(profile,(size_t) (i+1));
c=ReadBlobByte(image);
GetStringInfoDatum(profile)[i]=(unsigned char) c;
*p++=(char) c;
if ((strchr("\n\r%",c) == (char *) NULL) &&
((size_t) (p-command) < (MaxTextExtent-1)))
continue;
*p='\0';
p=command;
if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0)
break;
}
SetStringInfoLength(profile,(size_t) i);
(void) SetImageProfile(image,"xmp",profile);
profile=DestroyStringInfo(profile);
continue;
}
}
(void) CloseBlob(image);
if (image_info->number_scenes != 0)
{
Image
*clone_image;
register ssize_t
i;
/*
Add place holder images to meet the subimage specification requirement.
*/
for (i=0; i < (ssize_t) image_info->scene; i++)
{
clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception);
if (clone_image != (Image *) NULL)
PrependImageToList(&postscript_image,clone_image);
}
}
do
{
(void) CopyMagickString(postscript_image->filename,filename,MaxTextExtent);
(void) CopyMagickString(postscript_image->magick,image->magick,
MaxTextExtent);
if (columns != 0)
postscript_image->magick_columns=columns;
if (rows != 0)
postscript_image->magick_rows=rows;
postscript_image->page=page;
(void) CloneImageProfiles(postscript_image,image);
(void) CloneImageProperties(postscript_image,image);
next=SyncNextImageInList(postscript_image);
if (next != (Image *) NULL)
postscript_image=next;
} while (next != (Image *) NULL);
image=DestroyImageList(image);
scene=0;
for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; )
{
next->scene=scene++;
next=GetNextImageInList(next);
}
return(GetFirstImageInList(postscript_image));
}
|
CWE-399
| 182,791 | 4,004 |
324044698586397428333670659503508729184
| null | null | null |
ImageMagick
|
cdb383749ef7b68a38891440af8cc23e0115306d
| 1 |
static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowCUTReaderException(severity,tag) \
{ \
if (palette != NULL) \
palette=DestroyImage(palette); \
if (clone_info != NULL) \
clone_info=DestroyImageInfo(clone_info); \
ThrowReaderException(severity,tag); \
}
Image *image,*palette;
ImageInfo *clone_info;
MagickBooleanType status;
MagickOffsetType
offset;
size_t EncodedByte;
unsigned char RunCount,RunValue,RunCountMasked;
CUTHeader Header;
CUTPalHeader PalHeader;
ssize_t depth;
ssize_t i,j;
ssize_t ldblk;
unsigned char *BImgBuff=NULL,*ptrB;
register Quantum *q;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read CUT image.
*/
palette=NULL;
clone_info=NULL;
Header.Width=ReadBlobLSBShort(image);
Header.Height=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0)
CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
/*---This code checks first line of image---*/
EncodedByte=ReadBlobLSBShort(image);
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
ldblk=0;
while((int) RunCountMasked!=0) /*end of line?*/
{
i=1;
if((int) RunCount<0x80) i=(ssize_t) RunCountMasked;
offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET);
if (offset < 0)
ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/
EncodedByte-=i+1;
ldblk+=(ssize_t) RunCountMasked;
RunCount=(unsigned char) ReadBlobByte(image);
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/
RunCountMasked=RunCount & 0x7F;
}
if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/
i=0; /*guess a number of bit planes*/
if(ldblk==(int) Header.Width) i=8;
if(2*ldblk==(int) Header.Width) i=4;
if(8*ldblk==(int) Header.Width) i=1;
if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/
depth=i;
image->columns=Header.Width;
image->rows=Header.Height;
image->depth=8;
image->colors=(size_t) (GetQuantumRange(1UL*i)+1);
if (image_info->ping != MagickFalse) goto Finish;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/* ----- Do something with palette ----- */
if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette;
i=(ssize_t) strlen(clone_info->filename);
j=i;
while(--i>0)
{
if(clone_info->filename[i]=='.')
{
break;
}
if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' ||
clone_info->filename[i]==':' )
{
i=j;
break;
}
}
(void) CopyMagickString(clone_info->filename+i,".PAL",(size_t)
(MagickPathExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
(void) CopyMagickString(clone_info->filename+i,".pal",(size_t)
(MagickPathExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info->filename[i]='\0';
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info=DestroyImageInfo(clone_info);
clone_info=NULL;
goto NoPalette;
}
}
}
if( (palette=AcquireImage(clone_info,exception))==NULL ) goto NoPalette;
status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ErasePalette:
palette=DestroyImage(palette);
palette=NULL;
goto NoPalette;
}
if(palette!=NULL)
{
(void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId);
if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette;
PalHeader.Version=ReadBlobLSBShort(palette);
PalHeader.Size=ReadBlobLSBShort(palette);
PalHeader.FileType=(char) ReadBlobByte(palette);
PalHeader.SubType=(char) ReadBlobByte(palette);
PalHeader.BoardID=ReadBlobLSBShort(palette);
PalHeader.GraphicsMode=ReadBlobLSBShort(palette);
PalHeader.MaxIndex=ReadBlobLSBShort(palette);
PalHeader.MaxRed=ReadBlobLSBShort(palette);
PalHeader.MaxGreen=ReadBlobLSBShort(palette);
PalHeader.MaxBlue=ReadBlobLSBShort(palette);
(void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId);
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
if(PalHeader.MaxIndex<1) goto ErasePalette;
image->colors=PalHeader.MaxIndex+1;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) goto NoMemory;
if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/
if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange;
if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange;
for(i=0;i<=(int) PalHeader.MaxIndex;i++)
{ /*this may be wrong- I don't know why is palette such strange*/
j=(ssize_t) TellBlob(palette);
if((j % 512)>512-6)
{
j=((j / 512)+1)*512;
offset=SeekBlob(palette,j,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxRed)
{
image->colormap[i].red=ClampToQuantum(((double)
image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/
PalHeader.MaxRed);
}
image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxGreen)
{
image->colormap[i].green=ClampToQuantum
(((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen);
}
image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxBlue)
{
image->colormap[i].blue=ClampToQuantum
(((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue);
}
}
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
NoPalette:
if(palette==NULL)
{
image->colors=256;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
{
NoMemory:
ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t)image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
}
/* ----- Load RLE compressed raster ----- */
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/
if(BImgBuff==NULL) goto NoMemory;
offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);
if (offset < 0)
{
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < (int) Header.Height; i++)
{
EncodedByte=ReadBlobLSBShort(image);
ptrB=BImgBuff;
j=ldblk;
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
while ((int) RunCountMasked != 0)
{
if((ssize_t) RunCountMasked>j)
{ /*Wrong Data*/
RunCountMasked=(unsigned char) j;
if(j==0)
{
break;
}
}
if((int) RunCount>0x80)
{
RunValue=(unsigned char) ReadBlobByte(image);
(void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked);
}
else {
(void) ReadBlob(image,(size_t) RunCountMasked,ptrB);
}
ptrB+=(int) RunCountMasked;
j-=(int) RunCountMasked;
if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
}
InsertRow(image,depth,BImgBuff,i,exception);
}
(void) SyncImage(image,exception);
/*detect monochrome image*/
if(palette==NULL)
{ /*attempt to detect binary (black&white) images*/
if ((image->storage_class == PseudoClass) &&
(SetImageGray(image,exception) != MagickFalse))
{
if(GetCutColors(image,exception)==2)
{
for (i=0; i < (ssize_t)image->colors; i++)
{
register Quantum
sample;
sample=ScaleCharToQuantum((unsigned char) i);
if(image->colormap[i].red!=sample) goto Finish;
if(image->colormap[i].green!=sample) goto Finish;
if(image->colormap[i].blue!=sample) goto Finish;
}
image->colormap[1].red=image->colormap[1].green=
image->colormap[1].blue=QuantumRange;
for (i=0; i < (ssize_t)image->rows; i++)
{
q=QueueAuthenticPixels(image,0,i,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (j=0; j < (ssize_t)image->columns; j++)
{
if (GetPixelRed(image,q) == ScaleCharToQuantum(1))
{
SetPixelRed(image,QuantumRange,q);
SetPixelGreen(image,QuantumRange,q);
SetPixelBlue(image,QuantumRange,q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish;
}
}
}
}
Finish:
if (BImgBuff != NULL)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
|
CWE-20
| 182,793 | 4,005 |
88863127355848595853296170247264235509
| null | null | null |
ImageMagick
|
fe3066122ef72c82415811d25e9e3fad622c0a99
| 1 |
static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
BMPInfo
bmp_info;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset,
profile_data,
profile_size,
start_position;
MemoryInfo
*pixel_info;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bit,
bytes_per_line,
length;
ssize_t
count,
y;
unsigned char
magick[12],
*pixels;
unsigned int
blue,
green,
offset_bits,
red;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a BMP file.
*/
(void) memset(&bmp_info,0,sizeof(bmp_info));
bmp_info.ba_offset=0;
start_position=0;
offset_bits=0;
count=ReadBlob(image,2,magick);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
PixelInfo
quantum_bits;
PixelPacket
shift;
/*
Verify BMP identifier.
*/
start_position=TellBlob(image)-2;
bmp_info.ba_offset=0;
while (LocaleNCompare((char *) magick,"BA",2) == 0)
{
bmp_info.file_size=ReadBlobLSBLong(image);
bmp_info.ba_offset=ReadBlobLSBLong(image);
bmp_info.offset_bits=ReadBlobLSBLong(image);
count=ReadBlob(image,2,magick);
if (count != 2)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c",
magick[0],magick[1]);
if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) &&
(LocaleNCompare((char *) magick,"CI",2) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bmp_info.file_size=ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image);
bmp_info.offset_bits=ReadBlobLSBLong(image);
bmp_info.size=ReadBlobLSBLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u",
bmp_info.size);
profile_data=0;
profile_size=0;
if (bmp_info.size == 12)
{
/*
OS/2 BMP image file.
*/
(void) CopyMagickString(image->magick,"BMP2",MagickPathExtent);
bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));
bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));
bmp_info.planes=ReadBlobLSBShort(image);
bmp_info.bits_per_pixel=ReadBlobLSBShort(image);
bmp_info.x_pixels=0;
bmp_info.y_pixels=0;
bmp_info.number_colors=0;
bmp_info.compression=BI_RGB;
bmp_info.image_size=0;
bmp_info.alpha_mask=0;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format: OS/2 Bitmap");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Geometry: %.20gx%.20g",(double) bmp_info.width,(double)
bmp_info.height);
}
}
else
{
/*
Microsoft Windows BMP image file.
*/
if (bmp_info.size < 40)
ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError");
bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);
bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);
bmp_info.planes=ReadBlobLSBShort(image);
bmp_info.bits_per_pixel=ReadBlobLSBShort(image);
bmp_info.compression=ReadBlobLSBLong(image);
bmp_info.image_size=ReadBlobLSBLong(image);
bmp_info.x_pixels=ReadBlobLSBLong(image);
bmp_info.y_pixels=ReadBlobLSBLong(image);
bmp_info.number_colors=ReadBlobLSBLong(image);
if ((MagickSizeType) bmp_info.number_colors > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
bmp_info.colors_important=ReadBlobLSBLong(image);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format: MS Windows bitmap");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Geometry: %.20gx%.20g",(double) bmp_info.width,(double)
bmp_info.height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel);
switch (bmp_info.compression)
{
case BI_RGB:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RGB");
break;
}
case BI_RLE4:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RLE4");
break;
}
case BI_RLE8:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RLE8");
break;
}
case BI_BITFIELDS:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_BITFIELDS");
break;
}
case BI_PNG:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_PNG");
break;
}
case BI_JPEG:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_JPEG");
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: UNKNOWN (%u)",bmp_info.compression);
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %u",bmp_info.number_colors);
}
bmp_info.red_mask=ReadBlobLSBLong(image);
bmp_info.green_mask=ReadBlobLSBLong(image);
bmp_info.blue_mask=ReadBlobLSBLong(image);
if (bmp_info.size > 40)
{
double
gamma;
/*
Read color management information.
*/
bmp_info.alpha_mask=ReadBlobLSBLong(image);
bmp_info.colorspace=ReadBlobLSBSignedLong(image);
/*
Decode 2^30 fixed point formatted CIE primaries.
*/
# define BMP_DENOM ((double) 0x40000000)
bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+
bmp_info.red_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.red_primary.x*=gamma;
bmp_info.red_primary.y*=gamma;
image->chromaticity.red_primary.x=bmp_info.red_primary.x;
image->chromaticity.red_primary.y=bmp_info.red_primary.y;
gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+
bmp_info.green_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.green_primary.x*=gamma;
bmp_info.green_primary.y*=gamma;
image->chromaticity.green_primary.x=bmp_info.green_primary.x;
image->chromaticity.green_primary.y=bmp_info.green_primary.y;
gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+
bmp_info.blue_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.blue_primary.x*=gamma;
bmp_info.blue_primary.y*=gamma;
image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;
image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;
/*
Decode 16^16 fixed point formatted gamma_scales.
*/
bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;
bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;
bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;
/*
Compute a single gamma from the BMP 3-channel gamma.
*/
image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+
bmp_info.gamma_scale.z)/3.0;
}
else
(void) CopyMagickString(image->magick,"BMP3",MagickPathExtent);
if (bmp_info.size > 108)
{
size_t
intent;
/*
Read BMP Version 5 color management information.
*/
intent=ReadBlobLSBLong(image);
switch ((int) intent)
{
case LCS_GM_BUSINESS:
{
image->rendering_intent=SaturationIntent;
break;
}
case LCS_GM_GRAPHICS:
{
image->rendering_intent=RelativeIntent;
break;
}
case LCS_GM_IMAGES:
{
image->rendering_intent=PerceptualIntent;
break;
}
case LCS_GM_ABS_COLORIMETRIC:
{
image->rendering_intent=AbsoluteIntent;
break;
}
}
profile_data=(MagickOffsetType)ReadBlobLSBLong(image);
profile_size=(MagickOffsetType)ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image); /* Reserved byte */
}
}
if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"LengthAndFilesizeDoNotMatch","`%s'",image->filename);
else
if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'",
image->filename);
if (bmp_info.width <= 0)
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
if (bmp_info.height == 0)
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
if (bmp_info.planes != 1)
ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne");
if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&
(bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&
(bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))
ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
if (bmp_info.bits_per_pixel < 16 &&
bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))
ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors");
if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))
ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))
ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))
ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
switch (bmp_info.compression)
{
case BI_RGB:
image->compression=NoCompression;
break;
case BI_RLE8:
case BI_RLE4:
image->compression=RLECompression;
break;
case BI_BITFIELDS:
break;
case BI_JPEG:
ThrowReaderException(CoderError,"JPEGCompressNotSupported");
case BI_PNG:
ThrowReaderException(CoderError,"PNGCompressNotSupported");
default:
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
}
image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);
image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);
image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;
image->alpha_trait=((bmp_info.alpha_mask != 0) &&
(bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait :
UndefinedPixelTrait;
if (bmp_info.bits_per_pixel < 16)
{
size_t
one;
image->storage_class=PseudoClass;
image->colors=bmp_info.number_colors;
one=1;
if (image->colors == 0)
image->colors=one << bmp_info.bits_per_pixel;
}
image->resolution.x=(double) bmp_info.x_pixels/100.0;
image->resolution.y=(double) bmp_info.y_pixels/100.0;
image->units=PixelsPerCentimeterResolution;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (image->storage_class == PseudoClass)
{
unsigned char
*bmp_colormap;
size_t
packet_size;
/*
Read BMP raster colormap.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading colormap of %.20g colors",(double) image->colors);
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
image->colors,4*sizeof(*bmp_colormap));
if (bmp_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((bmp_info.size == 12) || (bmp_info.size == 64))
packet_size=3;
else
packet_size=4;
offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);
if (offset < 0)
{
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,packet_size*image->colors,bmp_colormap);
if (count != (ssize_t) (packet_size*image->colors))
{
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=bmp_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++);
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++);
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++);
if (packet_size == 4)
p++;
}
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
}
/*
Read image data.
*/
if (bmp_info.offset_bits == offset_bits)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset_bits=bmp_info.offset_bits;
offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (bmp_info.compression == BI_RLE4)
bmp_info.bits_per_pixel<<=1;
bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
length=(size_t) bytes_per_line*image->rows;
if ((MagickSizeType) (length/256) > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
if ((bmp_info.compression == BI_RGB) ||
(bmp_info.compression == BI_BITFIELDS))
{
pixel_info=AcquireVirtualMemory(image->rows,
MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading pixels (%.20g bytes)",(double) length);
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
}
else
{
/*
Convert run-length encoded raster pixels.
*/
pixel_info=AcquireVirtualMemory(image->rows,
MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
status=DecodeImage(image,bmp_info.compression,pixels,
image->columns*image->rows);
if (status == MagickFalse)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnableToRunlengthDecodeImage");
}
}
/*
Convert BMP raster image to pixel packets.
*/
if (bmp_info.compression == BI_RGB)
{
/*
We should ignore the alpha value in BMP3 files but there have been
reports about 32 bit files with alpha. We do a quick check to see if
the alpha channel contains a value that is not zero (default value).
If we find a non zero value we asume the program that wrote the file
wants to use the alpha channel.
*/
if ((image->alpha_trait == UndefinedPixelTrait) &&
(bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32))
{
bytes_per_line=4*(image->columns);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (*(p+3) != 0)
{
image->alpha_trait=BlendPixelTrait;
y=-1;
break;
}
p+=4;
}
}
}
bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ?
0xff000000U : 0U;
bmp_info.red_mask=0x00ff0000U;
bmp_info.green_mask=0x0000ff00U;
bmp_info.blue_mask=0x000000ffU;
if (bmp_info.bits_per_pixel == 16)
{
/*
RGB555.
*/
bmp_info.red_mask=0x00007c00U;
bmp_info.green_mask=0x000003e0U;
bmp_info.blue_mask=0x0000001fU;
}
}
(void) memset(&shift,0,sizeof(shift));
(void) memset(&quantum_bits,0,sizeof(quantum_bits));
if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))
{
register unsigned int
sample;
/*
Get shift and quantum bits info from bitfield masks.
*/
if (bmp_info.red_mask != 0)
while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)
{
shift.red++;
if (shift.red >= 32U)
break;
}
if (bmp_info.green_mask != 0)
while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)
{
shift.green++;
if (shift.green >= 32U)
break;
}
if (bmp_info.blue_mask != 0)
while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)
{
shift.blue++;
if (shift.blue >= 32U)
break;
}
if (bmp_info.alpha_mask != 0)
while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0)
{
shift.alpha++;
if (shift.alpha >= 32U)
break;
}
sample=shift.red;
while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.red=(MagickRealType) (sample-shift.red);
sample=shift.green;
while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.green=(MagickRealType) (sample-shift.green);
sample=shift.blue;
while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.blue=(MagickRealType) (sample-shift.blue);
sample=shift.alpha;
while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.alpha=(MagickRealType) (sample-shift.alpha);
}
switch (bmp_info.bits_per_pixel)
{
case 1:
{
/*
Convert bitmap scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (image->columns % 8); bit++)
{
index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
break;
}
case 4:
{
/*
Convert PseudoColor scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 2) != 0)
{
ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
x++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
break;
}
case 8:
{
/*
Convert PseudoColor scanline.
*/
if ((bmp_info.compression == BI_RLE8) ||
(bmp_info.compression == BI_RLE4))
bytes_per_line=image->columns;
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=(ssize_t) image->columns; x != 0; --x)
{
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
break;
}
case 16:
{
unsigned int
alpha,
pixel;
/*
Convert bitfield encoded 16-bit PseudoColor scanline.
*/
if ((bmp_info.compression != BI_RGB) &&
(bmp_info.compression != BI_BITFIELDS))
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompression");
}
bytes_per_line=2*(image->columns+image->columns % 2);
image->storage_class=DirectClass;
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(unsigned int) (*p++);
pixel|=(*p++) << 8;
red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
if (quantum_bits.red == 5)
red|=((red & 0xe000) >> 5);
if (quantum_bits.red <= 8)
red|=((red & 0xff00) >> 8);
green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
if (quantum_bits.green == 5)
green|=((green & 0xe000) >> 5);
if (quantum_bits.green == 6)
green|=((green & 0xc000) >> 6);
if (quantum_bits.green <= 8)
green|=((green & 0xff00) >> 8);
blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
if (quantum_bits.blue == 5)
blue|=((blue & 0xe000) >> 5);
if (quantum_bits.blue <= 8)
blue|=((blue & 0xff00) >> 8);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
if (quantum_bits.alpha <= 8)
alpha|=((alpha & 0xff00) >> 8);
SetPixelAlpha(image,ScaleShortToQuantum(
(unsigned short) alpha),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 24:
{
/*
Convert DirectColor scanline.
*/
bytes_per_line=4*((image->columns*24+31)/32);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 32:
{
/*
Convert bitfield encoded DirectColor scanline.
*/
if ((bmp_info.compression != BI_RGB) &&
(bmp_info.compression != BI_BITFIELDS))
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompression");
}
bytes_per_line=4*(image->columns);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
unsigned int
alpha,
pixel;
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(unsigned int) (*p++);
pixel|=((unsigned int) *p++ << 8);
pixel|=((unsigned int) *p++ << 16);
pixel|=((unsigned int) *p++ << 24);
red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
if (quantum_bits.red == 8)
red|=(red >> 8);
green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
if (quantum_bits.green == 8)
green|=(green >> 8);
blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
if (quantum_bits.blue == 8)
blue|=(blue >> 8);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
if (quantum_bits.alpha == 8)
alpha|=(alpha >> 8);
SetPixelAlpha(image,ScaleShortToQuantum(
(unsigned short) alpha),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
default:
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (y > 0)
break;
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if (bmp_info.height < 0)
{
Image
*flipped_image;
/*
Correct image orientation.
*/
flipped_image=FlipImage(image,exception);
if (flipped_image != (Image *) NULL)
{
DuplicateBlob(flipped_image,image);
ReplaceImageInList(&image, flipped_image);
image=flipped_image;
}
}
/*
Read embeded ICC profile
*/
if ((bmp_info.colorspace == 0x4D424544L) && (profile_data > 0) &&
(profile_size > 0))
{
StringInfo
*profile;
unsigned char
*datum;
offset=start_position+14+profile_data;
if ((offset < TellBlob(image)) ||
(SeekBlob(image,offset,SEEK_SET) != offset) ||
(GetBlobSize(image) < (MagickSizeType) (offset+profile_size)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
profile=AcquireStringInfo((size_t) profile_size);
if (profile == (StringInfo *) NULL)
ThrowReaderException(CorruptImageError,"MemoryAllocationFailed");
datum=GetStringInfoDatum(profile);
if (ReadBlob(image,(size_t) profile_size,datum) == (ssize_t) profile_size)
{
MagickOffsetType
profile_size_orig;
/*
Trimming padded bytes.
*/
profile_size_orig=(MagickOffsetType) datum[0] << 24;
profile_size_orig|=(MagickOffsetType) datum[1] << 16;
profile_size_orig|=(MagickOffsetType) datum[2] << 8;
profile_size_orig|=(MagickOffsetType) datum[3];
if (profile_size_orig < profile_size)
SetStringInfoLength(profile,(size_t) profile_size_orig);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: ICC, %u bytes",(unsigned int) profile_size_orig);
(void) SetImageProfile(image,"icc",profile,exception);
}
profile=DestroyStringInfo(profile);
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
offset=(MagickOffsetType) bmp_info.ba_offset;
if (offset != 0)
if ((offset < TellBlob(image)) ||
(SeekBlob(image,offset,SEEK_SET) != offset))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
*magick='\0';
count=ReadBlob(image,2,magick);
if ((count == 2) && (IsBMP(magick,2) != MagickFalse))
{
/*
Acquire next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (IsBMP(magick,2) != MagickFalse);
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
|
CWE-399
| 182,794 | 4,006 |
86565001831407065949126777270293766681
| null | null | null |
ImageMagick
|
fe3066122ef72c82415811d25e9e3fad622c0a99
| 1 |
static Image *ReadVIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define VFF_CM_genericRGB 15
#define VFF_CM_ntscRGB 1
#define VFF_CM_NONE 0
#define VFF_DEP_DECORDER 0x4
#define VFF_DEP_NSORDER 0x8
#define VFF_DES_RAW 0
#define VFF_LOC_IMPLICIT 1
#define VFF_MAPTYP_NONE 0
#define VFF_MAPTYP_1_BYTE 1
#define VFF_MAPTYP_2_BYTE 2
#define VFF_MAPTYP_4_BYTE 4
#define VFF_MAPTYP_FLOAT 5
#define VFF_MAPTYP_DOUBLE 7
#define VFF_MS_NONE 0
#define VFF_MS_ONEPERBAND 1
#define VFF_MS_SHARED 3
#define VFF_TYP_BIT 0
#define VFF_TYP_1_BYTE 1
#define VFF_TYP_2_BYTE 2
#define VFF_TYP_4_BYTE 4
#define VFF_TYP_FLOAT 5
#define VFF_TYP_DOUBLE 9
typedef struct _ViffInfo
{
unsigned char
identifier,
file_type,
release,
version,
machine_dependency,
reserve[3];
char
comment[512];
unsigned int
rows,
columns,
subrows;
int
x_offset,
y_offset;
float
x_bits_per_pixel,
y_bits_per_pixel;
unsigned int
location_type,
location_dimension,
number_of_images,
number_data_bands,
data_storage_type,
data_encode_scheme,
map_scheme,
map_storage_type,
map_rows,
map_columns,
map_subrows,
map_enable,
maps_per_cycle,
color_space_model;
} ViffInfo;
double
min_value,
scale_factor,
value;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bytes_per_pixel,
max_packets,
quantum;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned long
lsb_first;
ViffInfo
viff_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read VIFF header (1024 bytes).
*/
count=ReadBlob(image,1,&viff_info.identifier);
do
{
/*
Verify VIFF identifier.
*/
if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab))
ThrowReaderException(CorruptImageError,"NotAVIFFImage");
/*
Initialize VIFF image.
*/
(void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type);
(void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release);
(void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version);
(void) ReadBlob(image,sizeof(viff_info.machine_dependency),
&viff_info.machine_dependency);
(void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve);
count=ReadBlob(image,512,(unsigned char *) viff_info.comment);
if (count != 512)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
viff_info.comment[511]='\0';
if (strlen(viff_info.comment) > 4)
(void) SetImageProperty(image,"comment",viff_info.comment,exception);
if ((viff_info.machine_dependency == VFF_DEP_DECORDER) ||
(viff_info.machine_dependency == VFF_DEP_NSORDER))
image->endian=LSBEndian;
else
image->endian=MSBEndian;
viff_info.rows=ReadBlobLong(image);
viff_info.columns=ReadBlobLong(image);
viff_info.subrows=ReadBlobLong(image);
viff_info.x_offset=ReadBlobSignedLong(image);
viff_info.y_offset=ReadBlobSignedLong(image);
viff_info.x_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.y_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.location_type=ReadBlobLong(image);
viff_info.location_dimension=ReadBlobLong(image);
viff_info.number_of_images=ReadBlobLong(image);
viff_info.number_data_bands=ReadBlobLong(image);
viff_info.data_storage_type=ReadBlobLong(image);
viff_info.data_encode_scheme=ReadBlobLong(image);
viff_info.map_scheme=ReadBlobLong(image);
viff_info.map_storage_type=ReadBlobLong(image);
viff_info.map_rows=ReadBlobLong(image);
viff_info.map_columns=ReadBlobLong(image);
viff_info.map_subrows=ReadBlobLong(image);
viff_info.map_enable=ReadBlobLong(image);
viff_info.maps_per_cycle=ReadBlobLong(image);
viff_info.color_space_model=ReadBlobLong(image);
for (i=0; i < 420; i++)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows;
if (number_pixels > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
if (number_pixels != (size_t) number_pixels)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (number_pixels == 0)
ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported");
image->columns=viff_info.rows;
image->rows=viff_info.columns;
image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL :
MAGICKCORE_QUANTUM_DEPTH;
image->alpha_trait=viff_info.number_data_bands == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) SetImageBackgroundColor(image,exception);
/*
Verify that we can read this VIFF image.
*/
if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((viff_info.data_storage_type != VFF_TYP_BIT) &&
(viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_2_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_4_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_FLOAT) &&
(viff_info.data_storage_type != VFF_TYP_DOUBLE))
ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported");
if (viff_info.data_encode_scheme != VFF_DES_RAW)
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) &&
(viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_FLOAT) &&
(viff_info.map_storage_type != VFF_MAPTYP_DOUBLE))
ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported");
if ((viff_info.color_space_model != VFF_CM_NONE) &&
(viff_info.color_space_model != VFF_CM_ntscRGB) &&
(viff_info.color_space_model != VFF_CM_genericRGB))
ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported");
if (viff_info.location_type != VFF_LOC_IMPLICIT)
ThrowReaderException(CoderError,"LocationTypeIsNotSupported");
if (viff_info.number_of_images != 1)
ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported");
if (viff_info.map_rows == 0)
viff_info.map_scheme=VFF_MS_NONE;
switch ((int) viff_info.map_scheme)
{
case VFF_MS_NONE:
{
if (viff_info.number_data_bands < 3)
{
/*
Create linear color ramp.
*/
if (viff_info.data_storage_type == VFF_TYP_BIT)
image->colors=2;
else
if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE)
image->colors=256UL;
else
image->colors=image->depth <= 8 ? 256UL : 65536UL;
status=AcquireImageColormap(image,image->colors,exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
break;
}
case VFF_MS_ONEPERBAND:
case VFF_MS_SHARED:
{
unsigned char
*viff_colormap;
/*
Allocate VIFF colormap.
*/
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break;
case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break;
case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
image->colors=viff_info.map_columns;
if ((MagickSizeType) (viff_info.map_rows*image->colors) > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((MagickSizeType) viff_info.map_rows > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
if ((MagickSizeType) viff_info.map_rows >
(viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap));
if (viff_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read VIFF raster colormap.
*/
count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows,
viff_colormap);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE:
{
MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
case VFF_MAPTYP_4_BYTE:
case VFF_MAPTYP_FLOAT:
{
MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
default: break;
}
for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++)
{
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break;
case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break;
case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break;
case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break;
default: value=1.0*viff_colormap[i]; break;
}
if (i < (ssize_t) image->colors)
{
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum((unsigned char) value);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum((unsigned char) value);
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum((unsigned char) value);
}
else
if (i < (ssize_t) (2*image->colors))
image->colormap[i % image->colors].green=(MagickRealType)
ScaleCharToQuantum((unsigned char) value);
else
if (i < (ssize_t) (3*image->colors))
image->colormap[i % image->colors].blue=(MagickRealType)
ScaleCharToQuantum((unsigned char) value);
}
viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (viff_info.data_storage_type == VFF_TYP_BIT)
{
/*
Create bi-level colormap.
*/
image->colors=2;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image->colorspace=GRAYColorspace;
}
/*
Allocate VIFF pixels.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_TYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_TYP_FLOAT: bytes_per_pixel=4; break;
case VFF_TYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
if (viff_info.data_storage_type == VFF_TYP_BIT)
{
if (HeapOverflowSanityCheck((image->columns+7UL) >> 3UL,image->rows) != MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
max_packets=((image->columns+7UL) >> 3UL)*image->rows;
}
else
{
if (HeapOverflowSanityCheck((size_t) number_pixels,viff_info.number_data_bands) != MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
max_packets=(size_t) (number_pixels*viff_info.number_data_bands);
}
if ((MagickSizeType) (bytes_per_pixel*max_packets) > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
pixels=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(
number_pixels,max_packets),bytes_per_pixel*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(pixels,0,MagickMax(number_pixels,max_packets)*
bytes_per_pixel*sizeof(*pixels));
count=ReadBlob(image,bytes_per_pixel*max_packets,pixels);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE:
{
MSBOrderShort(pixels,bytes_per_pixel*max_packets);
break;
}
case VFF_TYP_4_BYTE:
case VFF_TYP_FLOAT:
{
MSBOrderLong(pixels,bytes_per_pixel*max_packets);
break;
}
default: break;
}
min_value=0.0;
scale_factor=1.0;
if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.map_scheme == VFF_MS_NONE))
{
double
max_value;
/*
Determine scale factor.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break;
default: value=1.0*pixels[0]; break;
}
max_value=value;
min_value=value;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (value > max_value)
max_value=value;
else
if (value < min_value)
min_value=value;
}
if ((min_value == 0) && (max_value == 0))
scale_factor=0;
else
if (min_value == max_value)
{
scale_factor=(double) QuantumRange/min_value;
min_value=0;
}
else
scale_factor=(double) QuantumRange/(max_value-min_value);
}
/*
Convert pixels to Quantum size.
*/
p=(unsigned char *) pixels;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (viff_info.map_scheme == VFF_MS_NONE)
{
value=(value-min_value)*scale_factor;
if (value > QuantumRange)
value=QuantumRange;
else
if (value < 0)
value=0;
}
*p=(unsigned char) ((Quantum) value);
p++;
}
/*
Convert VIFF raster image to pixel packets.
*/
p=(unsigned char *) pixels;
if (viff_info.data_storage_type == VFF_TYP_BIT)
{
/*
Convert bitmap scanline.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) (image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q);
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) quantum,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (int) (image->columns % 8); bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q);
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) quantum,q);
q+=GetPixelChannels(image);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
if (image->storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
{
/*
Convert DirectColor scanline.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+number_pixels)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2*number_pixels)),q);
if (image->colors != 0)
{
ssize_t
index;
index=(ssize_t) GetPixelRed(image,q);
SetPixelRed(image,ClampToQuantum(image->colormap[
ConstrainColormapIndex(image,index,exception)].red),q);
index=(ssize_t) GetPixelGreen(image,q);
SetPixelGreen(image,ClampToQuantum(image->colormap[
ConstrainColormapIndex(image,index,exception)].green),q);
index=(ssize_t) GetPixelBlue(image,q);
SetPixelBlue(image,ClampToQuantum(image->colormap[
ConstrainColormapIndex(image,index,exception)].blue),q);
}
SetPixelAlpha(image,image->alpha_trait != UndefinedPixelTrait ?
ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueAlpha,q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
count=ReadBlob(image,1,&viff_info.identifier);
if ((count == 1) && (viff_info.identifier == 0xab))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (viff_info.identifier == 0xab));
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
|
CWE-399
| 182,795 | 4,007 |
105511065680299742989440191999372843293
| null | null | null |
libming
|
2be22fcf56a223dafe8de0e8a20fe20e8bbdb0b9
| 1 |
decompileAction(int n, SWF_ACTION *actions, int maxn)
{
if( n > maxn ) SWF_error("Action overflow!!");
#ifdef DEBUG
fprintf(stderr,"%d:\tACTION[%3.3d]: %s\n",
actions[n].SWF_ACTIONRECORD.Offset, n,
actionName(actions[n].SWF_ACTIONRECORD.ActionCode));
#endif
switch(actions[n].SWF_ACTIONRECORD.ActionCode)
{
case SWFACTION_END:
return 0;
case SWFACTION_CONSTANTPOOL:
decompileCONSTANTPOOL(&actions[n]);
return 0;
case SWFACTION_GOTOLABEL:
return decompileGOTOFRAME(n, actions, maxn,1);
case SWFACTION_GOTOFRAME:
return decompileGOTOFRAME(n, actions, maxn,0);
case SWFACTION_GOTOFRAME2:
return decompileGOTOFRAME2(n, actions, maxn);
case SWFACTION_WAITFORFRAME:
decompileWAITFORFRAME(&actions[n]);
return 0;
case SWFACTION_GETURL2:
decompileGETURL2(&actions[n]);
return 0;
case SWFACTION_GETURL:
decompileGETURL(&actions[n]);
return 0;
case SWFACTION_PUSH:
decompilePUSH(&actions[n]);
return 0;
case SWFACTION_PUSHDUP:
decompilePUSHDUP(&actions[n]);
return 0;
case SWFACTION_STACKSWAP:
decompileSTACKSWAP(&actions[n]);
return 0;
case SWFACTION_SETPROPERTY:
decompileSETPROPERTY(n, actions, maxn);
return 0;
case SWFACTION_GETPROPERTY:
decompileGETPROPERTY(n, actions, maxn);
return 0;
case SWFACTION_GETTIME:
return decompileGETTIME(n, actions, maxn);
case SWFACTION_TRACE:
decompileTRACE(n, actions, maxn);
return 0;
case SWFACTION_CALLFRAME:
decompileCALLFRAME(n, actions, maxn);
return 0;
case SWFACTION_EXTENDS:
decompileEXTENDS(n, actions, maxn);
return 0;
case SWFACTION_INITOBJECT:
decompileINITOBJECT(n, actions, maxn);
return 0;
case SWFACTION_NEWOBJECT:
decompileNEWOBJECT(n, actions, maxn);
return 0;
case SWFACTION_NEWMETHOD:
decompileNEWMETHOD(n, actions, maxn);
return 0;
case SWFACTION_GETMEMBER:
decompileGETMEMBER(n, actions, maxn);
return 0;
case SWFACTION_SETMEMBER:
decompileSETMEMBER(n, actions, maxn);
return 0;
case SWFACTION_GETVARIABLE:
decompileGETVARIABLE(n, actions, maxn);
return 0;
case SWFACTION_SETVARIABLE:
decompileSETVARIABLE(n, actions, maxn, 0);
return 0;
case SWFACTION_DEFINELOCAL:
decompileSETVARIABLE(n, actions, maxn, 1);
return 0;
case SWFACTION_DEFINELOCAL2:
decompileDEFINELOCAL2(n, actions, maxn);
return 0;
case SWFACTION_DECREMENT:
return decompileINCR_DECR(n, actions, maxn, 0);
case SWFACTION_INCREMENT:
return decompileINCR_DECR(n, actions, maxn,1);
case SWFACTION_STOREREGISTER:
decompileSTOREREGISTER(n, actions, maxn);
return 0;
case SWFACTION_JUMP:
return decompileJUMP(n, actions, maxn);
case SWFACTION_RETURN:
decompileRETURN(n, actions, maxn);
return 0;
case SWFACTION_LOGICALNOT:
return decompileLogicalNot(n, actions, maxn);
case SWFACTION_IF:
return decompileIF(n, actions, maxn);
case SWFACTION_WITH:
decompileWITH(n, actions, maxn);
return 0;
case SWFACTION_ENUMERATE:
return decompileENUMERATE(n, actions, maxn, 0);
case SWFACTION_ENUMERATE2 :
return decompileENUMERATE(n, actions, maxn,1);
case SWFACTION_INITARRAY:
return decompileINITARRAY(n, actions, maxn);
case SWFACTION_DEFINEFUNCTION:
return decompileDEFINEFUNCTION(n, actions, maxn,0);
case SWFACTION_DEFINEFUNCTION2:
return decompileDEFINEFUNCTION(n, actions, maxn,1);
case SWFACTION_CALLFUNCTION:
return decompileCALLFUNCTION(n, actions, maxn);
case SWFACTION_CALLMETHOD:
return decompileCALLMETHOD(n, actions, maxn);
case SWFACTION_INSTANCEOF:
case SWFACTION_SHIFTLEFT:
case SWFACTION_SHIFTRIGHT:
case SWFACTION_SHIFTRIGHT2:
case SWFACTION_ADD:
case SWFACTION_ADD2:
case SWFACTION_SUBTRACT:
case SWFACTION_MULTIPLY:
case SWFACTION_DIVIDE:
case SWFACTION_MODULO:
case SWFACTION_BITWISEAND:
case SWFACTION_BITWISEOR:
case SWFACTION_BITWISEXOR:
case SWFACTION_EQUAL:
case SWFACTION_EQUALS2:
case SWFACTION_LESS2:
case SWFACTION_LOGICALAND:
case SWFACTION_LOGICALOR:
case SWFACTION_GREATER:
case SWFACTION_LESSTHAN:
case SWFACTION_STRINGEQ:
case SWFACTION_STRINGCOMPARE:
case SWFACTION_STRICTEQUALS:
return decompileArithmeticOp(n, actions, maxn);
case SWFACTION_POP:
pop();
return 0;
case SWFACTION_STARTDRAG:
return decompileSTARTDRAG(n, actions, maxn);
case SWFACTION_DELETE:
return decompileDELETE(n, actions, maxn,0);
case SWFACTION_DELETE2:
return decompileDELETE(n, actions, maxn,1);
case SWFACTION_TARGETPATH:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"targetPath");
case SWFACTION_TYPEOF:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"typeof");
case SWFACTION_ORD:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"ord");
case SWFACTION_CHR:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"chr");
case SWFACTION_INT:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"int");
case SWFACTION_TOSTRING:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"String");
case SWFACTION_TONUMBER:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"Number");
case SWFACTION_RANDOMNUMBER:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"random");
case SWFACTION_STRINGLENGTH:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"length");
case SWFACTION_PLAY:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"play");
case SWFACTION_STOP:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"stop");
case SWFACTION_NEXTFRAME:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"nextFrame");
case SWFACTION_PREVFRAME:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"prevFrame");
case SWFACTION_ENDDRAG:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"stopDrag");
case SWFACTION_STOPSOUNDS:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"stopAllSounds");
case SWFACTION_TOGGLEQUALITY:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"toggleHighQuality");
case SWFACTION_MBSUBSTRING:
case SWFACTION_SUBSTRING:
return decompileSUBSTRING(n, actions, maxn);
case SWFACTION_STRINGCONCAT:
return decompileSTRINGCONCAT(n, actions, maxn);
case SWFACTION_REMOVECLIP:
return decompileREMOVECLIP(n, actions, maxn);
case SWFACTION_DUPLICATECLIP:
return decompileDUPLICATECLIP(n, actions, maxn);
case SWFACTION_SETTARGET:
return decompileSETTARGET(n, actions, maxn,0);
case SWFACTION_SETTARGET2:
return decompileSETTARGET(n, actions, maxn,1);
case SWFACTION_IMPLEMENTSOP:
return decompileIMPLEMENTS(n, actions, maxn);
case SWFACTION_CASTOP:
return decompileCAST(n, actions, maxn);
case SWFACTION_THROW:
return decompileTHROW(n, actions, maxn);
case SWFACTION_TRY:
return decompileTRY(n, actions, maxn);
default:
outputSWF_ACTION(n,&actions[n]);
return 0;
}
}
|
CWE-119
| 182,818 | 4,025 |
125508971660947635203177119955891669032
| null | null | null |
libming
|
3dc0338e4a36a3092720ebaa5b908ba3dca467d9
| 1 |
SWFShape_setLeftFillStyle(SWFShape shape, SWFFillStyle fill)
{
ShapeRecord record;
int idx;
if ( shape->isEnded || shape->isMorph )
return;
if(fill == NOFILL)
{
record = addStyleRecord(shape);
record.record.stateChange->leftFill = 0;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
return;
}
idx = getFillIdx(shape, fill);
if(idx == 0) // fill not present in array
{
SWFFillStyle_addDependency(fill, (SWFCharacter)shape);
if(addFillStyle(shape, fill) < 0)
return;
idx = getFillIdx(shape, fill);
}
record = addStyleRecord(shape);
record.record.stateChange->leftFill = idx;
record.record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG;
}
|
CWE-119
| 182,819 | 4,026 |
22722777434440267512255572468198292338
| null | null | null |
libming
|
2223f7a1e431455a1411bee77c90db94a6f8e8fe
| 1 |
SWFInput_readSBits(SWFInput input, int number)
{
int num = SWFInput_readBits(input, number);
if ( num & (1<<(number-1)) )
return num - (1<<number);
else
return num;
}
|
CWE-190
| 182,820 | 4,027 |
263739449907377668792020882724555830333
| null | null | null |
openjpeg
|
8ee335227bbcaf1614124046aa25e53d67b11ec3
| 1 |
static OPJ_BOOL bmp_read_rle8_data(FILE* IN, OPJ_UINT8* pData,
OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 x, y;
OPJ_UINT8 *pix;
const OPJ_UINT8 *beyond;
beyond = pData + stride * height;
pix = pData;
x = y = 0U;
while (y < height) {
int c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
if (c) {
int j, c1_int;
OPJ_UINT8 c1;
c1_int = getc(IN);
if (c1_int == EOF) {
return OPJ_FALSE;
}
c1 = (OPJ_UINT8)c1_int;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
*pix = c1;
}
} else {
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
if (c == 0x00) { /* EOL */
x = 0;
++y;
pix = pData + y * stride + x;
} else if (c == 0x01) { /* EOP */
break;
} else if (c == 0x02) { /* MOVE by dxdy */
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
x += (OPJ_UINT32)c;
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
y += (OPJ_UINT32)c;
pix = pData + y * stride + x;
} else { /* 03 .. 255 */
int j;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
int c1_int;
OPJ_UINT8 c1;
c1_int = getc(IN);
if (c1_int == EOF) {
return OPJ_FALSE;
}
c1 = (OPJ_UINT8)c1_int;
*pix = c1;
}
if ((OPJ_UINT32)c & 1U) { /* skip padding byte */
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
}
}
}
}/* while() */
return OPJ_TRUE;
}
|
CWE-400
| 182,821 | 4,028 |
85511402824178127771642322355853124189
| null | null | null |
linux
|
6ff7b060535e87c2ae14dd8548512abfdda528fb
| 1 |
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;
}
|
CWE-416
| 182,824 | 4,031 |
332319665854404422071886214959160736764
| null | null | null |
linux
|
58bdd544e2933a21a51eecf17c3f5f94038261b5
| 1 |
static int nfc_llcp_build_gb(struct nfc_llcp_local *local)
{
u8 *gb_cur, *version_tlv, version, version_length;
u8 *lto_tlv, lto_length;
u8 *wks_tlv, wks_length;
u8 *miux_tlv, miux_length;
__be16 wks = cpu_to_be16(local->local_wks);
u8 gb_len = 0;
int ret = 0;
version = LLCP_VERSION_11;
version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version,
1, &version_length);
gb_len += version_length;
lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, <o_length);
gb_len += lto_length;
pr_debug("Local wks 0x%lx\n", local->local_wks);
wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length);
gb_len += wks_length;
miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0,
&miux_length);
gb_len += miux_length;
gb_len += ARRAY_SIZE(llcp_magic);
if (gb_len > NFC_MAX_GT_LEN) {
ret = -EINVAL;
goto out;
}
gb_cur = local->gb;
memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic));
gb_cur += ARRAY_SIZE(llcp_magic);
memcpy(gb_cur, version_tlv, version_length);
gb_cur += version_length;
memcpy(gb_cur, lto_tlv, lto_length);
gb_cur += lto_length;
memcpy(gb_cur, wks_tlv, wks_length);
gb_cur += wks_length;
memcpy(gb_cur, miux_tlv, miux_length);
gb_cur += miux_length;
local->gb_len = gb_len;
out:
kfree(version_tlv);
kfree(lto_tlv);
kfree(wks_tlv);
kfree(miux_tlv);
return ret;
}
|
CWE-476
| 182,827 | 4,034 |
276762293576136116287177850574897295346
| null | null | null |
bubblewrap
|
efc89e3b939b4bde42c10f065f6b7b02958ed50e
| 1 |
main (int argc,
char **argv)
{
mode_t old_umask;
cleanup_free char *base_path = NULL;
int clone_flags;
char *old_cwd = NULL;
pid_t pid;
int event_fd = -1;
int child_wait_fd = -1;
int setup_finished_pipe[] = {-1, -1};
const char *new_cwd;
uid_t ns_uid;
gid_t ns_gid;
struct stat sbuf;
uint64_t val;
int res UNUSED;
cleanup_free char *seccomp_data = NULL;
size_t seccomp_len;
struct sock_fprog seccomp_prog;
cleanup_free char *args_data = NULL;
/* Handle --version early on before we try to acquire/drop
* any capabilities so it works in a build environment;
* right now flatpak's build runs bubblewrap --version.
* https://github.com/projectatomic/bubblewrap/issues/185
*/
if (argc == 2 && (strcmp (argv[1], "--version") == 0))
print_version_and_exit ();
real_uid = getuid ();
real_gid = getgid ();
/* Get the (optional) privileges we need */
acquire_privs ();
/* Never gain any more privs during exec */
if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0)
die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed");
/* The initial code is run with high permissions
(i.e. CAP_SYS_ADMIN), so take lots of care. */
read_overflowids ();
argv0 = argv[0];
if (isatty (1))
host_tty_dev = ttyname (1);
argv++;
argc--;
if (argc == 0)
usage (EXIT_FAILURE, stderr);
parse_args (&argc, (const char ***) &argv);
/* suck the args into a cleanup_free variable to control their lifecycle */
args_data = opt_args_data;
opt_args_data = NULL;
if ((requested_caps[0] || requested_caps[1]) && is_privileged)
die ("--cap-add in setuid mode can be used only by root");
if (opt_userns_block_fd != -1 && !opt_unshare_user)
die ("--userns-block-fd requires --unshare-user");
if (opt_userns_block_fd != -1 && opt_info_fd == -1)
die ("--userns-block-fd requires --info-fd");
/* We have to do this if we weren't installed setuid (and we're not
* root), so let's just DWIM */
if (!is_privileged && getuid () != 0)
opt_unshare_user = TRUE;
#ifdef ENABLE_REQUIRE_USERNS
/* In this build option, we require userns. */
if (is_privileged && getuid () != 0)
opt_unshare_user = TRUE;
#endif
if (opt_unshare_user_try &&
stat ("/proc/self/ns/user", &sbuf) == 0)
{
bool disabled = FALSE;
/* RHEL7 has a kernel module parameter that lets you enable user namespaces */
if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0)
{
cleanup_free char *enable = NULL;
enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable");
if (enable != NULL && enable[0] == 'N')
disabled = TRUE;
}
/* Check for max_user_namespaces */
if (stat ("/proc/sys/user/max_user_namespaces", &sbuf) == 0)
{
cleanup_free char *max_user_ns = NULL;
max_user_ns = load_file_at (AT_FDCWD, "/proc/sys/user/max_user_namespaces");
if (max_user_ns != NULL && strcmp(max_user_ns, "0\n") == 0)
disabled = TRUE;
}
/* Debian lets you disable *unprivileged* user namespaces. However this is not
a problem if we're privileged, and if we're not opt_unshare_user is TRUE
already, and there is not much we can do, its just a non-working setup. */
if (!disabled)
opt_unshare_user = TRUE;
}
if (argc == 0)
usage (EXIT_FAILURE, stderr);
__debug__ (("Creating root mount point\n"));
if (opt_sandbox_uid == -1)
opt_sandbox_uid = real_uid;
if (opt_sandbox_gid == -1)
opt_sandbox_gid = real_gid;
if (!opt_unshare_user && opt_sandbox_uid != real_uid)
die ("Specifying --uid requires --unshare-user");
if (!opt_unshare_user && opt_sandbox_gid != real_gid)
die ("Specifying --gid requires --unshare-user");
if (!opt_unshare_uts && opt_sandbox_hostname != NULL)
die ("Specifying --hostname requires --unshare-uts");
if (opt_as_pid_1 && !opt_unshare_pid)
die ("Specifying --as-pid-1 requires --unshare-pid");
if (opt_as_pid_1 && lock_files != NULL)
die ("Specifying --as-pid-1 and --lock-file is not permitted");
/* We need to read stuff from proc during the pivot_root dance, etc.
Lets keep a fd to it open */
proc_fd = open ("/proc", O_PATH);
if (proc_fd == -1)
die_with_error ("Can't open /proc");
/* We need *some* mountpoint where we can mount the root tmpfs.
We first try in /run, and if that fails, try in /tmp. */
base_path = xasprintf ("/run/user/%d/.bubblewrap", real_uid);
if (ensure_dir (base_path, 0755))
{
free (base_path);
base_path = xasprintf ("/tmp/.bubblewrap-%d", real_uid);
if (ensure_dir (base_path, 0755))
die_with_error ("Creating root mountpoint failed");
}
__debug__ (("creating new namespace\n"));
if (opt_unshare_pid && !opt_as_pid_1)
{
event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK);
if (event_fd == -1)
die_with_error ("eventfd()");
}
/* We block sigchild here so that we can use signalfd in the monitor. */
block_sigchild ();
clone_flags = SIGCHLD | CLONE_NEWNS;
if (opt_unshare_user)
clone_flags |= CLONE_NEWUSER;
if (opt_unshare_pid)
clone_flags |= CLONE_NEWPID;
if (opt_unshare_net)
clone_flags |= CLONE_NEWNET;
if (opt_unshare_ipc)
clone_flags |= CLONE_NEWIPC;
if (opt_unshare_uts)
clone_flags |= CLONE_NEWUTS;
if (opt_unshare_cgroup)
{
if (stat ("/proc/self/ns/cgroup", &sbuf))
{
if (errno == ENOENT)
die ("Cannot create new cgroup namespace because the kernel does not support it");
else
die_with_error ("stat on /proc/self/ns/cgroup failed");
}
clone_flags |= CLONE_NEWCGROUP;
}
if (opt_unshare_cgroup_try)
if (!stat ("/proc/self/ns/cgroup", &sbuf))
clone_flags |= CLONE_NEWCGROUP;
child_wait_fd = eventfd (0, EFD_CLOEXEC);
if (child_wait_fd == -1)
die_with_error ("eventfd()");
/* Track whether pre-exec setup finished if we're reporting process exit */
if (opt_json_status_fd != -1)
{
int ret;
ret = pipe2 (setup_finished_pipe, O_CLOEXEC);
if (ret == -1)
die_with_error ("pipe2()");
}
pid = raw_clone (clone_flags, NULL);
if (pid == -1)
{
if (opt_unshare_user)
{
if (errno == EINVAL)
die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems.");
else if (errno == EPERM && !is_privileged)
die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'.");
}
die_with_error ("Creating new namespace failed");
}
ns_uid = opt_sandbox_uid;
ns_gid = opt_sandbox_gid;
if (pid != 0)
{
/* Parent, outside sandbox, privileged (initially) */
if (is_privileged && opt_unshare_user && opt_userns_block_fd == -1)
{
/* We're running as euid 0, but the uid we want to map is
* not 0. This means we're not allowed to write this from
* the child user namespace, so we do it from the parent.
*
* Also, we map uid/gid 0 in the namespace (to overflowuid)
* if opt_needs_devpts is true, because otherwise the mount
* of devpts fails due to root not being mapped.
*/
write_uid_gid_map (ns_uid, real_uid,
ns_gid, real_gid,
pid, TRUE, opt_needs_devpts);
}
/* Initial launched process, wait for exec:ed command to exit */
/* We don't need any privileges in the launcher, drop them immediately. */
drop_privs (FALSE);
/* Optionally bind our lifecycle to that of the parent */
handle_die_with_parent ();
if (opt_info_fd != -1)
{
cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i\n}\n", pid);
dump_info (opt_info_fd, output, TRUE);
close (opt_info_fd);
}
if (opt_json_status_fd != -1)
{
cleanup_free char *output = xasprintf ("{ \"child-pid\": %i }\n", pid);
dump_info (opt_json_status_fd, output, TRUE);
}
if (opt_userns_block_fd != -1)
{
char b[1];
(void) TEMP_FAILURE_RETRY (read (opt_userns_block_fd, b, 1));
close (opt_userns_block_fd);
}
/* Let child run now that the uid maps are set up */
val = 1;
res = write (child_wait_fd, &val, 8);
/* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */
close (child_wait_fd);
return monitor_child (event_fd, pid, setup_finished_pipe[0]);
}
/* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user).
*
* Note that for user namespaces we run as euid 0 during clone(), so
* the child user namespace is owned by euid 0., This means that the
* regular user namespace parent (with uid != 0) doesn't have any
* capabilities in it, which is nice as we can't exploit those. In
* particular the parent user namespace doesn't have CAP_PTRACE
* which would otherwise allow the parent to hijack of the child
* after this point.
*
* Unfortunately this also means you can't ptrace the final
* sandboxed process from outside the sandbox either.
*/
if (opt_info_fd != -1)
close (opt_info_fd);
if (opt_json_status_fd != -1)
close (opt_json_status_fd);
/* Wait for the parent to init uid/gid maps and drop caps */
res = read (child_wait_fd, &val, 8);
close (child_wait_fd);
/* At this point we can completely drop root uid, but retain the
* required permitted caps. This allow us to do full setup as
* the user uid, which makes e.g. fuse access work.
*/
switch_to_user_with_privs ();
if (opt_unshare_net)
loopback_setup (); /* Will exit if unsuccessful */
ns_uid = opt_sandbox_uid;
ns_gid = opt_sandbox_gid;
if (!is_privileged && opt_unshare_user && opt_userns_block_fd == -1)
{
/* In the unprivileged case we have to write the uid/gid maps in
* the child, because we have no caps in the parent */
if (opt_needs_devpts)
{
/* This is a bit hacky, but we need to first map the real uid/gid to
0, otherwise we can't mount the devpts filesystem because root is
not mapped. Later we will create another child user namespace and
map back to the real uid */
ns_uid = 0;
ns_gid = 0;
}
write_uid_gid_map (ns_uid, real_uid,
ns_gid, real_gid,
-1, TRUE, FALSE);
}
old_umask = umask (0);
/* Need to do this before the chroot, but after we're the real uid */
resolve_symlinks_in_ops ();
/* Mark everything as slave, so that we still
* receive mounts from the real root, but don't
* propagate mounts to the real root. */
if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0)
die_with_error ("Failed to make / slave");
/* Create a tmpfs which we will use as / in the namespace */
if (mount ("tmpfs", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0)
die_with_error ("Failed to mount tmpfs");
old_cwd = get_current_dir_name ();
/* Chdir to the new root tmpfs mount. This will be the CWD during
the entire setup. Access old or new root via "oldroot" and "newroot". */
if (chdir (base_path) != 0)
die_with_error ("chdir base_path");
/* We create a subdir "$base_path/newroot" for the new root, that
* way we can pivot_root to base_path, and put the old root at
* "$base_path/oldroot". This avoids problems accessing the oldroot
* dir if the user requested to bind mount something over / */
if (mkdir ("newroot", 0755))
die_with_error ("Creating newroot failed");
if (mount ("newroot", "newroot", NULL, MS_MGC_VAL | MS_BIND | MS_REC, NULL) < 0)
die_with_error ("setting up newroot bind");
if (mkdir ("oldroot", 0755))
die_with_error ("Creating oldroot failed");
if (pivot_root (base_path, "oldroot"))
die_with_error ("pivot_root");
if (chdir ("/") != 0)
die_with_error ("chdir / (base path)");
if (is_privileged)
{
pid_t child;
int privsep_sockets[2];
if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0)
die_with_error ("Can't create privsep socket");
child = fork ();
if (child == -1)
die_with_error ("Can't fork unprivileged helper");
if (child == 0)
{
/* Unprivileged setup process */
drop_privs (FALSE);
close (privsep_sockets[0]);
setup_newroot (opt_unshare_pid, privsep_sockets[1]);
exit (0);
}
else
{
int status;
uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */
uint32_t op, flags;
const char *arg1, *arg2;
cleanup_fd int unpriv_socket = -1;
unpriv_socket = privsep_sockets[0];
close (privsep_sockets[1]);
do
{
op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer),
&flags, &arg1, &arg2);
privileged_op (-1, op, flags, arg1, arg2);
if (write (unpriv_socket, buffer, 1) != 1)
die ("Can't write to op_socket");
}
while (op != PRIV_SEP_OP_DONE);
waitpid (child, &status, 0);
/* Continue post setup */
}
}
else
{
setup_newroot (opt_unshare_pid, -1);
}
close_ops_fd ();
/* The old root better be rprivate or we will send unmount events to the parent namespace */
if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0)
die_with_error ("Failed to make old root rprivate");
if (umount2 ("oldroot", MNT_DETACH))
die_with_error ("unmount old root");
/* This is our second pivot. It's like we're a Silicon Valley startup flush
* with cash but short on ideas!
*
* We're aiming to make /newroot the real root, and get rid of /oldroot. To do
* that we need a temporary place to store it before we can unmount it.
*/
{ cleanup_fd int oldrootfd = open ("/", O_DIRECTORY | O_RDONLY);
if (oldrootfd < 0)
die_with_error ("can't open /");
if (chdir ("/newroot") != 0)
die_with_error ("chdir /newroot");
/* While the documentation claims that put_old must be underneath
* new_root, it is perfectly fine to use the same directory as the
* kernel checks only if old_root is accessible from new_root.
*
* Both runc and LXC are using this "alternative" method for
* setting up the root of the container:
*
* https://github.com/opencontainers/runc/blob/master/libcontainer/rootfs_linux.go#L671
* https://github.com/lxc/lxc/blob/master/src/lxc/conf.c#L1121
*/
if (pivot_root (".", ".") != 0)
die_with_error ("pivot_root(/newroot)");
if (fchdir (oldrootfd) < 0)
die_with_error ("fchdir to oldroot");
if (umount2 (".", MNT_DETACH) < 0)
die_with_error ("umount old root");
if (chdir ("/") != 0)
die_with_error ("chdir /");
}
if (opt_unshare_user &&
(ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid) &&
opt_userns_block_fd == -1)
{
/* Now that devpts is mounted and we've no need for mount
permissions we can create a new userspace and map our uid
1:1 */
if (unshare (CLONE_NEWUSER))
die_with_error ("unshare user ns");
write_uid_gid_map (opt_sandbox_uid, ns_uid,
opt_sandbox_gid, ns_gid,
-1, FALSE, FALSE);
}
/* All privileged ops are done now, so drop caps we don't need */
drop_privs (!is_privileged);
if (opt_block_fd != -1)
{
char b[1];
(void) TEMP_FAILURE_RETRY (read (opt_block_fd, b, 1));
close (opt_block_fd);
}
if (opt_seccomp_fd != -1)
{
seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len);
if (seccomp_data == NULL)
die_with_error ("Can't read seccomp data");
if (seccomp_len % 8 != 0)
die ("Invalid seccomp data, must be multiple of 8");
seccomp_prog.len = seccomp_len / 8;
seccomp_prog.filter = (struct sock_filter *) seccomp_data;
close (opt_seccomp_fd);
}
umask (old_umask);
new_cwd = "/";
if (opt_chdir_path)
{
if (chdir (opt_chdir_path))
die_with_error ("Can't chdir to %s", opt_chdir_path);
new_cwd = opt_chdir_path;
}
else if (chdir (old_cwd) == 0)
{
/* If the old cwd is mapped in the sandbox, go there */
new_cwd = old_cwd;
}
else
{
/* If the old cwd is not mapped, go to home */
const char *home = getenv ("HOME");
if (home != NULL &&
chdir (home) == 0)
new_cwd = home;
}
xsetenv ("PWD", new_cwd, 1);
free (old_cwd);
if (opt_new_session &&
setsid () == (pid_t) -1)
die_with_error ("setsid");
if (label_exec (opt_exec_label) == -1)
die_with_error ("label_exec %s", argv[0]);
__debug__ (("forking for child\n"));
if (!opt_as_pid_1 && (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1))
{
/* We have to have a pid 1 in the pid namespace, because
* otherwise we'll get a bunch of zombies as nothing reaps
* them. Alternatively if we're using sync_fd or lock_files we
* need some process to own these.
*/
pid = fork ();
if (pid == -1)
die_with_error ("Can't fork for pid 1");
if (pid != 0)
{
drop_all_caps (FALSE);
/* Close fds in pid 1, except stdio and optionally event_fd
(for syncing pid 2 lifetime with monitor_child) and
opt_sync_fd (for syncing sandbox lifetime with outside
process).
Any other fds will been passed on to the child though. */
{
int dont_close[3];
int j = 0;
if (event_fd != -1)
dont_close[j++] = event_fd;
if (opt_sync_fd != -1)
dont_close[j++] = opt_sync_fd;
dont_close[j++] = -1;
fdwalk (proc_fd, close_extra_fds, dont_close);
}
return do_init (event_fd, pid, seccomp_data != NULL ? &seccomp_prog : NULL);
}
}
__debug__ (("launch executable %s\n", argv[0]));
if (proc_fd != -1)
close (proc_fd);
/* If we are using --as-pid-1 leak the sync fd into the sandbox.
--sync-fd will still work unless the container process doesn't close this file. */
if (!opt_as_pid_1)
{
if (opt_sync_fd != -1)
close (opt_sync_fd);
}
/* We want sigchild in the child */
unblock_sigchild ();
/* Optionally bind our lifecycle */
handle_die_with_parent ();
if (!is_privileged)
set_ambient_capabilities ();
/* Should be the last thing before execve() so that filters don't
* need to handle anything above */
if (seccomp_data != NULL &&
prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &seccomp_prog) != 0)
die_with_error ("prctl(PR_SET_SECCOMP)");
if (setup_finished_pipe[1] != -1)
{
char data = 0;
res = write_to_fd (setup_finished_pipe[1], &data, 1);
/* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]
we don't want to error out here */
}
if (execvp (argv[0], argv) == -1)
{
if (setup_finished_pipe[1] != -1)
{
int saved_errno = errno;
char data = 0;
res = write_to_fd (setup_finished_pipe[1], &data, 1);
errno = saved_errno;
/* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]
we don't want to error out here */
}
die_with_error ("execvp %s", argv[0]);
}
return 0;
}
|
CWE-20
| 182,832 | 4,038 |
41291708509448163055090816521581584694
| null | null | null |
miniupnp
|
cb8a02af7a5677cf608e86d57ab04241cf34e24f
| 1 |
static void copyIPv6IfDifferent(void * dest, const void * src)
{
if(dest != src) {
memcpy(dest, src, sizeof(struct in6_addr));
}
}
|
CWE-476
| 182,837 | 4,039 |
329926470648283772929714392568937645066
| null | null | null |
miniupnp
|
f321c2066b96d18afa5158dfa2d2873a2957ef38
| 1 |
upnp_redirect(const char * rhost, unsigned short eport,
const char * iaddr, unsigned short iport,
const char * protocol, const char * desc,
unsigned int leaseduration)
{
int proto, r;
char iaddr_old[32];
char rhost_old[32];
unsigned short iport_old;
struct in_addr address;
unsigned int timestamp;
proto = proto_atoi(protocol);
if(inet_aton(iaddr, &address) <= 0) {
syslog(LOG_ERR, "inet_aton(%s) FAILED", iaddr);
return -1;
}
if(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm,
eport, address, iport)) {
syslog(LOG_INFO, "redirection permission check failed for "
"%hu->%s:%hu %s", eport, iaddr, iport, protocol);
return -3;
}
/* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001)
* - 2.2.20.PortMappingDescription :
* Overwriting Previous / Existing Port Mappings:
* If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient
* are exactly the same as an existing mapping, the existing mapping values
* for InternalPort, PortMappingDescription, PortMappingEnabled and
* PortMappingLeaseDuration are overwritten.
* Rejecting a New Port Mapping:
* In cases where the RemoteHost, ExternalPort and PortMappingProtocol
* are the same as an existing mapping, but the InternalClient is
* different, the action is rejected with an appropriate error.
* Add or Reject New Port Mapping behavior based on vendor implementation:
* In cases where the ExternalPort, PortMappingProtocol and InternalClient
* are the same, but RemoteHost is different, the vendor can choose to
* support both mappings simultaneously, or reject the second mapping
* with an appropriate error.
*
* - 2.4.16.AddPortMapping
* This action creates a new port mapping or overwrites an existing
* mapping with the same internal client. If the ExternalPort and
* PortMappingProtocol pair is already mapped to another internal client,
* an error is returned.
*
* IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010)
* Protocol ExternalPort RemoteHost InternalClient Result
* = = ≠ ≠ Failure
* = = ≠ = Failure or success
* (vendor specific)
* = = = ≠ Failure
* = = = = Success (overwrite)
*/
rhost_old[0] = '\0';
r = get_redirect_rule(ext_if_name, eport, proto,
iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0,
rhost_old, sizeof(rhost_old),
×tamp, 0, 0);
if(r == 0) {
if(strcmp(iaddr, iaddr_old)==0 &&
((rhost == NULL && rhost_old[0]=='\0') ||
(rhost && (strcmp(rhost, "*") == 0) && rhost_old[0]=='\0') ||
(rhost && (strcmp(rhost, rhost_old) == 0)))) {
syslog(LOG_INFO, "updating existing port mapping %hu %s (rhost '%s') => %s:%hu",
eport, protocol, rhost_old, iaddr_old, iport_old);
timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;
if(iport != iport_old) {
r = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp);
} else {
r = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp);
}
#ifdef ENABLE_LEASEFILE
if(r == 0) {
lease_file_remove(eport, proto);
lease_file_add(eport, iaddr, iport, proto, desc, timestamp);
}
#endif /* ENABLE_LEASEFILE */
return r;
} else {
syslog(LOG_INFO, "port %hu %s (rhost '%s') already redirected to %s:%hu",
eport, protocol, rhost_old, iaddr_old, iport_old);
return -2;
}
#ifdef CHECK_PORTINUSE
} else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) {
syslog(LOG_INFO, "port %hu protocol %s already in use",
eport, protocol);
return -4;
#endif /* CHECK_PORTINUSE */
} else {
timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;
syslog(LOG_INFO, "redirecting port %hu to %s:%hu protocol %s for: %s",
eport, iaddr, iport, protocol, desc);
return upnp_redirect_internal(rhost, eport, iaddr, iport, proto,
desc, timestamp);
}
}
|
CWE-476
| 182,838 | 4,040 |
46344349630705210442777134508681564817
| null | null | null |
miniupnp
|
13585f15c7f7dc28bbbba1661efb280d530d114c
| 1 |
GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
|
CWE-476
| 182,839 | 4,041 |
158973129754763104915389678544268410746
| null | null | null |
miniupnp
|
cd506a67e174a45c6a202eff182a712955ed6d6f
| 1 |
updateDevice(const struct header * headers, time_t t)
{
struct device ** pp = &devlist;
struct device * p = *pp; /* = devlist; */
while(p)
{
if( p->headers[HEADER_NT].l == headers[HEADER_NT].l
&& (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))
&& p->headers[HEADER_USN].l == headers[HEADER_USN].l
&& (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )
{
/*printf("found! %d\n", (int)(t - p->t));*/
syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
p->t = t;
/* update Location ! */
if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l)
{
struct device * tmp;
tmp = realloc(p, sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l);
if(!tmp) /* allocation error */
{
syslog(LOG_ERR, "updateDevice() : memory allocation error");
free(p);
return 0;
}
p = tmp;
*pp = p;
}
memcpy(p->data + p->headers[0].l + p->headers[1].l,
headers[2].p, headers[2].l);
/* TODO : check p->headers[HEADER_LOCATION].l */
return 0;
}
pp = &p->next;
p = *pp; /* p = p->next; */
}
syslog(LOG_INFO, "new device discovered : %.*s",
headers[HEADER_USN].l, headers[HEADER_USN].p);
/* add */
{
char * pc;
int i;
p = malloc( sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l );
if(!p) {
syslog(LOG_ERR, "updateDevice(): cannot allocate memory");
return -1;
}
p->next = devlist;
p->t = t;
pc = p->data;
for(i = 0; i < 3; i++)
{
p->headers[i].p = pc;
p->headers[i].l = headers[i].l;
memcpy(pc, headers[i].p, headers[i].l);
pc += headers[i].l;
}
devlist = p;
sendNotifications(NOTIF_NEW, p, NULL);
}
return 1;
}
|
CWE-416
| 182,841 | 4,042 |
221734464000496160033465612690455954287
| null | null | null |
heimdal
|
2f7f3d9960aa6ea21358bdf3687cee5149aa35cf
| 1 |
krb5_init_creds_step(krb5_context context,
krb5_init_creds_context ctx,
krb5_data *in,
krb5_data *out,
krb5_krbhst_info *hostinfo,
unsigned int *flags)
{
krb5_error_code ret;
size_t len = 0;
size_t size;
AS_REQ req2;
krb5_data_zero(out);
if (ctx->as_req.req_body.cname == NULL) {
ret = init_as_req(context, ctx->flags, &ctx->cred,
ctx->addrs, ctx->etypes, &ctx->as_req);
if (ret) {
free_init_creds_ctx(context, ctx);
return ret;
}
}
#define MAX_PA_COUNTER 10
if (ctx->pa_counter > MAX_PA_COUNTER) {
krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
N_("Looping %d times while getting "
"initial credentials", ""),
ctx->pa_counter);
return KRB5_GET_IN_TKT_LOOP;
}
ctx->pa_counter++;
_krb5_debug(context, 5, "krb5_get_init_creds: loop %d", ctx->pa_counter);
/* Lets process the input packet */
if (in && in->length) {
krb5_kdc_rep rep;
memset(&rep, 0, sizeof(rep));
_krb5_debug(context, 5, "krb5_get_init_creds: processing input");
ret = decode_AS_REP(in->data, in->length, &rep.kdc_rep, &size);
if (ret == 0) {
unsigned eflags = EXTRACT_TICKET_AS_REQ | EXTRACT_TICKET_TIMESYNC;
krb5_data data;
/*
* Unwrap AS-REP
*/
ASN1_MALLOC_ENCODE(Ticket, data.data, data.length,
&rep.kdc_rep.ticket, &size, ret);
if (ret)
goto out;
heim_assert(data.length == size, "ASN.1 internal error");
ret = fast_unwrap_as_rep(context, ctx->nonce, &data,
&ctx->fast_state, &rep.kdc_rep);
krb5_data_free(&data);
if (ret)
goto out;
/*
* Now check and extract the ticket
*/
if (ctx->flags.canonicalize) {
eflags |= EXTRACT_TICKET_ALLOW_SERVER_MISMATCH;
eflags |= EXTRACT_TICKET_MATCH_REALM;
}
if (ctx->ic_flags & KRB5_INIT_CREDS_NO_C_CANON_CHECK)
eflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;
ret = process_pa_data_to_key(context, ctx, &ctx->cred,
&ctx->as_req, &rep.kdc_rep,
hostinfo, &ctx->fast_state.reply_key);
if (ret) {
free_AS_REP(&rep.kdc_rep);
goto out;
}
_krb5_debug(context, 5, "krb5_get_init_creds: extracting ticket");
ret = _krb5_extract_ticket(context,
&rep,
&ctx->cred,
ctx->fast_state.reply_key,
NULL,
KRB5_KU_AS_REP_ENC_PART,
NULL,
ctx->nonce,
eflags,
&ctx->req_buffer,
NULL,
NULL);
if (ret == 0)
ret = copy_EncKDCRepPart(&rep.enc_part, &ctx->enc_part);
krb5_free_keyblock(context, ctx->fast_state.reply_key);
ctx->fast_state.reply_key = NULL;
*flags = 0;
free_AS_REP(&rep.kdc_rep);
free_EncASRepPart(&rep.enc_part);
return ret;
} else {
/* let's try to parse it as a KRB-ERROR */
_krb5_debug(context, 5, "krb5_get_init_creds: got an error");
free_KRB_ERROR(&ctx->error);
ret = krb5_rd_error(context, in, &ctx->error);
if(ret && in->length && ((char*)in->data)[0] == 4)
ret = KRB5KRB_AP_ERR_V4_REPLY;
if (ret) {
_krb5_debug(context, 5, "krb5_get_init_creds: failed to read error");
goto out;
}
/*
* Unwrap KRB-ERROR
*/
ret = fast_unwrap_error(context, &ctx->fast_state, &ctx->error);
if (ret)
goto out;
/*
*
*/
ret = krb5_error_from_rd_error(context, &ctx->error, &ctx->cred);
_krb5_debug(context, 5, "krb5_get_init_creds: KRB-ERROR %d", ret);
/*
* If no preauth was set and KDC requires it, give it one
* more try.
*/
if (ret == KRB5KDC_ERR_PREAUTH_REQUIRED) {
free_METHOD_DATA(&ctx->md);
memset(&ctx->md, 0, sizeof(ctx->md));
if (ctx->error.e_data) {
ret = decode_METHOD_DATA(ctx->error.e_data->data,
ctx->error.e_data->length,
&ctx->md,
NULL);
if (ret)
krb5_set_error_message(context, ret,
N_("Failed to decode METHOD-DATA", ""));
} else {
krb5_set_error_message(context, ret,
N_("Preauth required but no preauth "
"options send by KDC", ""));
}
} else if (ret == KRB5KRB_AP_ERR_SKEW && context->kdc_sec_offset == 0) {
/*
* Try adapt to timeskrew when we are using pre-auth, and
* if there was a time skew, try again.
*/
krb5_set_real_time(context, ctx->error.stime, -1);
if (context->kdc_sec_offset)
ret = 0;
_krb5_debug(context, 10, "init_creds: err skew updateing kdc offset to %d",
context->kdc_sec_offset);
ctx->used_pa_types = 0;
} else if (ret == KRB5_KDC_ERR_WRONG_REALM && ctx->flags.canonicalize) {
/* client referal to a new realm */
if (ctx->error.crealm == NULL) {
krb5_set_error_message(context, ret,
N_("Got a client referral, not but no realm", ""));
goto out;
}
_krb5_debug(context, 5,
"krb5_get_init_creds: got referal to realm %s",
*ctx->error.crealm);
ret = krb5_principal_set_realm(context,
ctx->cred.client,
*ctx->error.crealm);
if (ret)
goto out;
if (krb5_principal_is_krbtgt(context, ctx->cred.server)) {
ret = krb5_init_creds_set_service(context, ctx, NULL);
if (ret)
goto out;
}
free_AS_REQ(&ctx->as_req);
memset(&ctx->as_req, 0, sizeof(ctx->as_req));
ctx->used_pa_types = 0;
} else if (ret == KRB5KDC_ERR_KEY_EXP && ctx->runflags.change_password == 0 && ctx->prompter) {
char buf2[1024];
ctx->runflags.change_password = 1;
ctx->prompter(context, ctx->prompter_data, NULL, N_("Password has expired", ""), 0, NULL);
/* try to avoid recursion */
if (ctx->in_tkt_service != NULL && strcmp(ctx->in_tkt_service, "kadmin/changepw") == 0)
goto out;
/* don't try to change password where then where none */
if (ctx->prompter == NULL)
goto out;
ret = change_password(context,
ctx->cred.client,
ctx->password,
buf2,
sizeof(buf2),
ctx->prompter,
ctx->prompter_data,
NULL);
if (ret)
goto out;
krb5_init_creds_set_password(context, ctx, buf2);
ctx->used_pa_types = 0;
ret = 0;
} else if (ret == KRB5KDC_ERR_PREAUTH_FAILED) {
if (ctx->fast_state.flags & KRB5_FAST_DISABLED)
goto out;
if (ctx->fast_state.flags & (KRB5_FAST_REQUIRED | KRB5_FAST_EXPECTED))
goto out;
_krb5_debug(context, 10, "preauth failed with FAST, "
"and told by KD or user, trying w/o FAST");
ctx->fast_state.flags |= KRB5_FAST_DISABLED;
ctx->used_pa_types = 0;
ret = 0;
}
if (ret)
goto out;
}
}
if (ctx->as_req.req_body.cname == NULL) {
ret = init_as_req(context, ctx->flags, &ctx->cred,
ctx->addrs, ctx->etypes, &ctx->as_req);
if (ret) {
free_init_creds_ctx(context, ctx);
return ret;
}
}
if (ctx->as_req.padata) {
free_METHOD_DATA(ctx->as_req.padata);
free(ctx->as_req.padata);
ctx->as_req.padata = NULL;
}
/* Set a new nonce. */
ctx->as_req.req_body.nonce = ctx->nonce;
/* fill_in_md_data */
ret = process_pa_data_to_md(context, &ctx->cred, &ctx->as_req, ctx,
&ctx->md, &ctx->as_req.padata,
ctx->prompter, ctx->prompter_data);
if (ret)
goto out;
/*
* Wrap with FAST
*/
copy_AS_REQ(&ctx->as_req, &req2);
ret = fast_wrap_req(context, &ctx->fast_state, &req2);
if (ret) {
free_AS_REQ(&req2);
goto out;
}
krb5_data_free(&ctx->req_buffer);
ASN1_MALLOC_ENCODE(AS_REQ,
ctx->req_buffer.data, ctx->req_buffer.length,
&req2, &len, ret);
free_AS_REQ(&req2);
if (ret)
goto out;
if(len != ctx->req_buffer.length)
krb5_abortx(context, "internal error in ASN.1 encoder");
out->data = ctx->req_buffer.data;
out->length = ctx->req_buffer.length;
*flags = KRB5_INIT_CREDS_STEP_FLAG_CONTINUE;
return 0;
out:
return ret;
}
|
CWE-320
| 182,842 | 4,043 |
261068004113217347553768999154811786683
| null | null | null |
linux
|
a1616a5ac99ede5d605047a9012481ce7ff18b16
| 1 |
static int do_hidp_sock_ioctl(struct socket *sock, unsigned int cmd, void __user *argp)
{
struct hidp_connadd_req ca;
struct hidp_conndel_req cd;
struct hidp_connlist_req cl;
struct hidp_conninfo ci;
struct socket *csock;
struct socket *isock;
int err;
BT_DBG("cmd %x arg %p", cmd, argp);
switch (cmd) {
case HIDPCONNADD:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&ca, argp, sizeof(ca)))
return -EFAULT;
csock = sockfd_lookup(ca.ctrl_sock, &err);
if (!csock)
return err;
isock = sockfd_lookup(ca.intr_sock, &err);
if (!isock) {
sockfd_put(csock);
return err;
}
err = hidp_connection_add(&ca, csock, isock);
if (!err && copy_to_user(argp, &ca, sizeof(ca)))
err = -EFAULT;
sockfd_put(csock);
sockfd_put(isock);
return err;
case HIDPCONNDEL:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&cd, argp, sizeof(cd)))
return -EFAULT;
return hidp_connection_del(&cd);
case HIDPGETCONNLIST:
if (copy_from_user(&cl, argp, sizeof(cl)))
return -EFAULT;
if (cl.cnum <= 0)
return -EINVAL;
err = hidp_get_connlist(&cl);
if (!err && copy_to_user(argp, &cl, sizeof(cl)))
return -EFAULT;
return err;
case HIDPGETCONNINFO:
if (copy_from_user(&ci, argp, sizeof(ci)))
return -EFAULT;
err = hidp_get_conninfo(&ci);
if (!err && copy_to_user(argp, &ci, sizeof(ci)))
return -EFAULT;
return err;
}
return -EINVAL;
}
|
CWE-77
| 182,848 | 4,049 |
190362082081650331138259506079741652797
| null | null | null |
linux
|
cb66ddd156203daefb8d71158036b27b0e2caf63
| 1 |
static void rds_tcp_kill_sock(struct net *net)
{
struct rds_tcp_connection *tc, *_tc;
LIST_HEAD(tmp_list);
struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);
struct socket *lsock = rtn->rds_tcp_listen_sock;
rtn->rds_tcp_listen_sock = NULL;
rds_tcp_listen_stop(lsock, &rtn->rds_tcp_accept_w);
spin_lock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {
struct net *c_net = read_pnet(&tc->t_cpath->cp_conn->c_net);
if (net != c_net || !tc->t_sock)
continue;
if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn)) {
list_move_tail(&tc->t_tcp_node, &tmp_list);
} else {
list_del(&tc->t_tcp_node);
tc->t_tcp_node_detached = true;
}
}
spin_unlock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)
rds_conn_destroy(tc->t_cpath->cp_conn);
}
|
CWE-362
| 182,851 | 4,052 |
8107321106413302302630832023180150150
| null | null | null |
linux
|
401e7e88d4ef80188ffa07095ac00456f901b8c4
| 1 |
static int try_smi_init(struct smi_info *new_smi)
{
int rv = 0;
int i;
char *init_name = NULL;
pr_info("Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\n",
ipmi_addr_src_to_str(new_smi->io.addr_source),
si_to_str[new_smi->io.si_type],
addr_space_to_str[new_smi->io.addr_type],
new_smi->io.addr_data,
new_smi->io.slave_addr, new_smi->io.irq);
switch (new_smi->io.si_type) {
case SI_KCS:
new_smi->handlers = &kcs_smi_handlers;
break;
case SI_SMIC:
new_smi->handlers = &smic_smi_handlers;
break;
case SI_BT:
new_smi->handlers = &bt_smi_handlers;
break;
default:
/* No support for anything else yet. */
rv = -EIO;
goto out_err;
}
new_smi->si_num = smi_num;
/* Do this early so it's available for logs. */
if (!new_smi->io.dev) {
init_name = kasprintf(GFP_KERNEL, "ipmi_si.%d",
new_smi->si_num);
/*
* If we don't already have a device from something
* else (like PCI), then register a new one.
*/
new_smi->pdev = platform_device_alloc("ipmi_si",
new_smi->si_num);
if (!new_smi->pdev) {
pr_err("Unable to allocate platform device\n");
rv = -ENOMEM;
goto out_err;
}
new_smi->io.dev = &new_smi->pdev->dev;
new_smi->io.dev->driver = &ipmi_platform_driver.driver;
/* Nulled by device_add() */
new_smi->io.dev->init_name = init_name;
}
/* Allocate the state machine's data and initialize it. */
new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL);
if (!new_smi->si_sm) {
rv = -ENOMEM;
goto out_err;
}
new_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm,
&new_smi->io);
/* Now that we know the I/O size, we can set up the I/O. */
rv = new_smi->io.io_setup(&new_smi->io);
if (rv) {
dev_err(new_smi->io.dev, "Could not set up I/O space\n");
goto out_err;
}
/* Do low-level detection first. */
if (new_smi->handlers->detect(new_smi->si_sm)) {
if (new_smi->io.addr_source)
dev_err(new_smi->io.dev,
"Interface detection failed\n");
rv = -ENODEV;
goto out_err;
}
/*
* Attempt a get device id command. If it fails, we probably
* don't have a BMC here.
*/
rv = try_get_dev_id(new_smi);
if (rv) {
if (new_smi->io.addr_source)
dev_err(new_smi->io.dev,
"There appears to be no BMC at this location\n");
goto out_err;
}
setup_oem_data_handler(new_smi);
setup_xaction_handlers(new_smi);
check_for_broken_irqs(new_smi);
new_smi->waiting_msg = NULL;
new_smi->curr_msg = NULL;
atomic_set(&new_smi->req_events, 0);
new_smi->run_to_completion = false;
for (i = 0; i < SI_NUM_STATS; i++)
atomic_set(&new_smi->stats[i], 0);
new_smi->interrupt_disabled = true;
atomic_set(&new_smi->need_watch, 0);
rv = try_enable_event_buffer(new_smi);
if (rv == 0)
new_smi->has_event_buffer = true;
/*
* Start clearing the flags before we enable interrupts or the
* timer to avoid racing with the timer.
*/
start_clear_flags(new_smi);
/*
* IRQ is defined to be set when non-zero. req_events will
* cause a global flags check that will enable interrupts.
*/
if (new_smi->io.irq) {
new_smi->interrupt_disabled = false;
atomic_set(&new_smi->req_events, 1);
}
if (new_smi->pdev && !new_smi->pdev_registered) {
rv = platform_device_add(new_smi->pdev);
if (rv) {
dev_err(new_smi->io.dev,
"Unable to register system interface device: %d\n",
rv);
goto out_err;
}
new_smi->pdev_registered = true;
}
dev_set_drvdata(new_smi->io.dev, new_smi);
rv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group);
if (rv) {
dev_err(new_smi->io.dev,
"Unable to add device attributes: error %d\n",
rv);
goto out_err;
}
new_smi->dev_group_added = true;
rv = ipmi_register_smi(&handlers,
new_smi,
new_smi->io.dev,
new_smi->io.slave_addr);
if (rv) {
dev_err(new_smi->io.dev,
"Unable to register device: error %d\n",
rv);
goto out_err;
}
/* Don't increment till we know we have succeeded. */
smi_num++;
dev_info(new_smi->io.dev, "IPMI %s interface initialized\n",
si_to_str[new_smi->io.si_type]);
WARN_ON(new_smi->io.dev->init_name != NULL);
out_err:
kfree(init_name);
return rv;
}
|
CWE-416
| 182,852 | 4,053 |
165864638601569777164331180070750501057
| null | null | null |
linux
|
401e7e88d4ef80188ffa07095ac00456f901b8c4
| 1 |
int ipmi_si_mem_setup(struct si_sm_io *io)
{
unsigned long addr = io->addr_data;
int mapsize, idx;
if (!addr)
return -ENODEV;
io->io_cleanup = mem_cleanup;
/*
* 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;
}
return 0;
}
|
CWE-416
| 182,853 | 4,054 |
268861984312861502465428053290581126604
| null | null | null |
linux
|
401e7e88d4ef80188ffa07095ac00456f901b8c4
| 1 |
int ipmi_si_port_setup(struct si_sm_io *io)
{
unsigned int addr = io->addr_data;
int idx;
if (!addr)
return -ENODEV;
io->io_cleanup = port_cleanup;
/*
* 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;
}
}
return 0;
}
|
CWE-416
| 182,854 | 4,055 |
46989818832240882763014773842282826433
| null | null | null |
linux
|
bcf3b67d16a4c8ffae0aa79de5853435e683945c
| 1 |
int megasas_alloc_cmds(struct megasas_instance *instance)
{
int i;
int j;
u16 max_cmd;
struct megasas_cmd *cmd;
max_cmd = instance->max_mfi_cmds;
/*
* instance->cmd_list is an array of struct megasas_cmd pointers.
* Allocate the dynamic array first and then allocate individual
* commands.
*/
instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
if (!instance->cmd_list) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n");
return -ENOMEM;
}
memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
for (i = 0; i < max_cmd; i++) {
instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
GFP_KERNEL);
if (!instance->cmd_list[i]) {
for (j = 0; j < i; j++)
kfree(instance->cmd_list[j]);
kfree(instance->cmd_list);
instance->cmd_list = NULL;
return -ENOMEM;
}
}
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
memset(cmd, 0, sizeof(struct megasas_cmd));
cmd->index = i;
cmd->scmd = NULL;
cmd->instance = instance;
list_add_tail(&cmd->list, &instance->cmd_pool);
}
/*
* Create a frame pool and assign one frame to each cmd
*/
if (megasas_create_frame_pool(instance)) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n");
megasas_free_cmds(instance);
}
return 0;
}
|
CWE-476
| 182,855 | 4,056 |
34156285142247751199109972261226060353
| null | null | null |
linux
|
04f5866e41fb70690e28397487d8bd8eea7d712a
| 1 |
void uverbs_user_mmap_disassociate(struct ib_uverbs_file *ufile)
{
struct rdma_umap_priv *priv, *next_priv;
lockdep_assert_held(&ufile->hw_destroy_rwsem);
while (1) {
struct mm_struct *mm = NULL;
/* Get an arbitrary mm pointer that hasn't been cleaned yet */
mutex_lock(&ufile->umap_lock);
while (!list_empty(&ufile->umaps)) {
int ret;
priv = list_first_entry(&ufile->umaps,
struct rdma_umap_priv, list);
mm = priv->vma->vm_mm;
ret = mmget_not_zero(mm);
if (!ret) {
list_del_init(&priv->list);
mm = NULL;
continue;
}
break;
}
mutex_unlock(&ufile->umap_lock);
if (!mm)
return;
/*
* The umap_lock is nested under mmap_sem since it used within
* the vma_ops callbacks, so we have to clean the list one mm
* at a time to get the lock ordering right. Typically there
* will only be one mm, so no big deal.
*/
down_write(&mm->mmap_sem);
mutex_lock(&ufile->umap_lock);
list_for_each_entry_safe (priv, next_priv, &ufile->umaps,
list) {
struct vm_area_struct *vma = priv->vma;
if (vma->vm_mm != mm)
continue;
list_del_init(&priv->list);
zap_vma_ptes(vma, vma->vm_start,
vma->vm_end - vma->vm_start);
vma->vm_flags &= ~(VM_SHARED | VM_MAYSHARE);
}
mutex_unlock(&ufile->umap_lock);
up_write(&mm->mmap_sem);
mmput(mm);
}
}
|
CWE-362
| 182,856 | 4,057 |
211043662189963803096096106338892197541
| null | null | null |
linux
|
04f5866e41fb70690e28397487d8bd8eea7d712a
| 1 |
static ssize_t clear_refs_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task;
char buffer[PROC_NUMBUF];
struct mm_struct *mm;
struct vm_area_struct *vma;
enum clear_refs_types type;
struct mmu_gather tlb;
int itype;
int rv;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
return -EFAULT;
rv = kstrtoint(strstrip(buffer), 10, &itype);
if (rv < 0)
return rv;
type = (enum clear_refs_types)itype;
if (type < CLEAR_REFS_ALL || type >= CLEAR_REFS_LAST)
return -EINVAL;
task = get_proc_task(file_inode(file));
if (!task)
return -ESRCH;
mm = get_task_mm(task);
if (mm) {
struct mmu_notifier_range range;
struct clear_refs_private cp = {
.type = type,
};
struct mm_walk clear_refs_walk = {
.pmd_entry = clear_refs_pte_range,
.test_walk = clear_refs_test_walk,
.mm = mm,
.private = &cp,
};
if (type == CLEAR_REFS_MM_HIWATER_RSS) {
if (down_write_killable(&mm->mmap_sem)) {
count = -EINTR;
goto out_mm;
}
/*
* Writing 5 to /proc/pid/clear_refs resets the peak
* resident set size to this mm's current rss value.
*/
reset_mm_hiwater_rss(mm);
up_write(&mm->mmap_sem);
goto out_mm;
}
down_read(&mm->mmap_sem);
tlb_gather_mmu(&tlb, mm, 0, -1);
if (type == CLEAR_REFS_SOFT_DIRTY) {
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (!(vma->vm_flags & VM_SOFTDIRTY))
continue;
up_read(&mm->mmap_sem);
if (down_write_killable(&mm->mmap_sem)) {
count = -EINTR;
goto out_mm;
}
for (vma = mm->mmap; vma; vma = vma->vm_next) {
vma->vm_flags &= ~VM_SOFTDIRTY;
vma_set_page_prot(vma);
}
downgrade_write(&mm->mmap_sem);
break;
}
mmu_notifier_range_init(&range, mm, 0, -1UL);
mmu_notifier_invalidate_range_start(&range);
}
walk_page_range(0, mm->highest_vm_end, &clear_refs_walk);
if (type == CLEAR_REFS_SOFT_DIRTY)
mmu_notifier_invalidate_range_end(&range);
tlb_finish_mmu(&tlb, 0, -1);
up_read(&mm->mmap_sem);
out_mm:
mmput(mm);
}
put_task_struct(task);
return count;
}
|
CWE-362
| 182,857 | 4,058 |
91277826670393984602661390281054078695
| null | null | null |
WavPack
|
bc6cba3f552c44565f7f1e66dc1580189addb2b4
| 1 |
int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int64_t infilesize, total_samples;
DFFFileHeader dff_file_header;
DFFChunkHeader dff_chunk_header;
uint32_t bcount;
infilesize = DoGetFileSize (infile);
memcpy (&dff_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) ||
bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
#if 1 // this might be a little too picky...
WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat);
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) {
error_line ("%s is not a valid .DFF file (by total size)!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("file header indicated length = %lld", dff_file_header.ckDataSize);
#endif
while (1) {
if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) ||
bcount != sizeof (DFFChunkHeader)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (debug_logging_mode)
error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize);
if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) {
uint32_t version;
if (dff_chunk_header.ckDataSize != sizeof (version) ||
!DoReadFile (infile, &version, sizeof (version), &bcount) ||
bcount != sizeof (version)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &version, sizeof (version))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&version, "L");
if (debug_logging_mode)
error_line ("dsdiff file version = 0x%08x", version);
}
else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) {
char *prop_chunk;
if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize);
prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) ||
bcount != dff_chunk_header.ckDataSize) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
if (!strncmp (prop_chunk, "SND ", 4)) {
char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize;
uint16_t numChannels = 0, chansSpecified, chanMask = 0;
uint32_t sampleRate;
while (eptr - cptr >= sizeof (dff_chunk_header)) {
memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header));
cptr += sizeof (dff_chunk_header);
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (dff_chunk_header.ckDataSize > 0 && dff_chunk_header.ckDataSize <= eptr - cptr) {
if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) {
memcpy (&sampleRate, cptr, sizeof (sampleRate));
WavpackBigEndianToNative (&sampleRate, "L");
cptr += dff_chunk_header.ckDataSize;
if (debug_logging_mode)
error_line ("got sample rate of %u Hz", sampleRate);
}
else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) {
memcpy (&numChannels, cptr, sizeof (numChannels));
WavpackBigEndianToNative (&numChannels, "S");
cptr += sizeof (numChannels);
chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4;
if (numChannels < chansSpecified || numChannels < 1 || numChannels > 256) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
while (chansSpecified--) {
if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4))
chanMask |= 0x1;
else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4))
chanMask |= 0x2;
else if (!strncmp (cptr, "LS ", 4))
chanMask |= 0x10;
else if (!strncmp (cptr, "RS ", 4))
chanMask |= 0x20;
else if (!strncmp (cptr, "C ", 4))
chanMask |= 0x4;
else if (!strncmp (cptr, "LFE ", 4))
chanMask |= 0x8;
else
if (debug_logging_mode)
error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]);
cptr += 4;
}
if (debug_logging_mode)
error_line ("%d channels, mask = 0x%08x", numChannels, chanMask);
}
else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) {
if (strncmp (cptr, "DSD ", 4)) {
error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!",
cptr [0], cptr [1], cptr [2], cptr [3]);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
cptr += dff_chunk_header.ckDataSize;
}
else {
if (debug_logging_mode)
error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0],
dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
cptr += dff_chunk_header.ckDataSize;
}
}
else {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
}
if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this DSDIFF file already has channel order information!");
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (chanMask)
config->channel_mask = chanMask;
config->bits_per_sample = 8;
config->bytes_per_sample = 1;
config->num_channels = numChannels;
config->sample_rate = sampleRate / 8;
config->qmode |= QMODE_DSD_MSB_FIRST;
}
else if (debug_logging_mode)
error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes",
prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize);
free (prop_chunk);
}
else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) {
if (!config->num_channels) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
total_samples = dff_chunk_header.ckDataSize / config->num_channels;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1);
char *buff;
if (bytes_to_copy < 0 || bytes_to_copy > 4194304) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2],
dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (debug_logging_mode)
error_line ("setting configuration with %lld samples", total_samples);
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
}
|
CWE-824
| 182,864 | 4,062 |
165237717197980297850368150837378570457
| null | null | null |
ImageMagick6
|
f663dfb8431c97d95682a2b533cca1c8233d21b4
| 1 |
static Image *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define CheckOverflowException(length,width,height) \
(((height) != 0) && ((length)/((size_t) height) != ((size_t) width)))
char
*comment;
Image
*image;
IndexPacket
index;
int
x_status;
MagickBooleanType
authentic_colormap;
MagickStatusType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register size_t
pixel;
size_t
length;
ssize_t
count,
y;
unsigned long
lsb_first;
XColor
*colors;
XImage
*ximage;
XWDFileHeader
header;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read in header information.
*/
count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header);
if (count != sz_XWDheader)
ThrowReaderException(CorruptImageError,"UnableToReadImageHeader");
/*
Ensure the header byte-order is most-significant byte first.
*/
lsb_first=1;
if ((int) (*(char *) &lsb_first) != 0)
MSBOrderLong((unsigned char *) &header,sz_XWDheader);
/*
Check to see if the dump file is in the proper format.
*/
if (header.file_version != XWD_FILE_VERSION)
ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch");
if (header.header_size < sz_XWDheader)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((header.bits_per_pixel == 0) || (header.bits_per_pixel > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (header.bitmap_unit > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (header.ncolors > 256)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
switch (header.visual_class)
{
case StaticGray:
case GrayScale:
case StaticColor:
case PseudoColor:
case TrueColor:
case DirectColor:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.pixmap_format)
{
case XYBitmap:
case XYPixmap:
case ZPixmap:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
length=(size_t) (header.header_size-sz_XWDheader);
if ((length+1) != ((size_t) ((CARD32) (length+1))))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length,(unsigned char *) comment);
comment[length]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
/*
Initialize the X image.
*/
ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage));
if (ximage == (XImage *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
ximage->depth=(int) header.pixmap_depth;
ximage->format=(int) header.pixmap_format;
ximage->xoffset=(int) header.xoffset;
ximage->data=(char *) NULL;
ximage->width=(int) header.pixmap_width;
ximage->height=(int) header.pixmap_height;
ximage->bitmap_pad=(int) header.bitmap_pad;
ximage->bytes_per_line=(int) header.bytes_per_line;
ximage->byte_order=(int) header.byte_order;
ximage->bitmap_unit=(int) header.bitmap_unit;
ximage->bitmap_bit_order=(int) header.bitmap_bit_order;
ximage->bits_per_pixel=(int) header.bits_per_pixel;
ximage->red_mask=header.red_mask;
ximage->green_mask=header.green_mask;
ximage->blue_mask=header.blue_mask;
if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) ||
(ximage->format < 0) || (ximage->byte_order < 0) ||
(ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) ||
(ximage->bytes_per_line < 0))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if ((ximage->width > 65535) || (ximage->height > 65535))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
x_status=XInitImage(ximage);
if (x_status == 0)
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
/*
Read colormap.
*/
authentic_colormap=MagickFalse;
colors=(XColor *) NULL;
if (header.ncolors != 0)
{
XWDColor
color;
length=(size_t) header.ncolors;
if (length > ((~0UL)/sizeof(*colors)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
colors=(XColor *) AcquireQuantumMemory(length,sizeof(*colors));
if (colors == (XColor *) NULL)
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) header.ncolors; i++)
{
count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color);
if (count != sz_XWDColor)
{
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
colors[i].pixel=color.pixel;
colors[i].red=color.red;
colors[i].green=color.green;
colors[i].blue=color.blue;
colors[i].flags=(char) color.flags;
if (color.flags != 0)
authentic_colormap=MagickTrue;
}
/*
Ensure the header byte-order is most-significant byte first.
*/
lsb_first=1;
if ((int) (*(char *) &lsb_first) != 0)
for (i=0; i < (ssize_t) header.ncolors; i++)
{
MSBOrderLong((unsigned char *) &colors[i].pixel,
sizeof(colors[i].pixel));
MSBOrderShort((unsigned char *) &colors[i].red,3*
sizeof(colors[i].red));
}
}
/*
Allocate the pixel buffer.
*/
length=(size_t) ximage->bytes_per_line*ximage->height;
if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height))
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (ximage->format != ZPixmap)
{
size_t
extent;
extent=length;
length*=ximage->depth;
if (CheckOverflowException(length,extent,ximage->depth))
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
}
ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data));
if (ximage->data == (char *) NULL)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
count=ReadBlob(image,length,(unsigned char *) ximage->data);
if (count != (ssize_t) length)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
/*
Convert image to MIFF format.
*/
image->columns=(size_t) ximage->width;
image->rows=(size_t) ximage->height;
image->depth=8;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if ((header.ncolors == 0U) || (ximage->red_mask != 0) ||
(ximage->green_mask != 0) || (ximage->blue_mask != 0))
image->storage_class=DirectClass;
else
image->storage_class=PseudoClass;
image->colors=header.ncolors;
if (image_info->ping == MagickFalse)
switch (image->storage_class)
{
case DirectClass:
default:
{
register size_t
color;
size_t
blue_mask,
blue_shift,
green_mask,
green_shift,
red_mask,
red_shift;
/*
Determine shift and mask for red, green, and blue.
*/
red_mask=ximage->red_mask;
red_shift=0;
while ((red_mask != 0) && ((red_mask & 0x01) == 0))
{
red_mask>>=1;
red_shift++;
}
green_mask=ximage->green_mask;
green_shift=0;
while ((green_mask != 0) && ((green_mask & 0x01) == 0))
{
green_mask>>=1;
green_shift++;
}
blue_mask=ximage->blue_mask;
blue_shift=0;
while ((blue_mask != 0) && ((blue_mask & 0x01) == 0))
{
blue_mask>>=1;
blue_shift++;
}
/*
Convert X image to DirectClass packets.
*/
if ((image->colors != 0) && (authentic_colormap != MagickFalse))
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=XGetPixel(ximage,(int) x,(int) y);
index=ConstrainColormapIndex(image,(ssize_t) (pixel >>
red_shift) & red_mask);
SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red));
index=ConstrainColormapIndex(image,(ssize_t) (pixel >>
green_shift) & green_mask);
SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t)
index].green));
index=ConstrainColormapIndex(image,(ssize_t) (pixel >>
blue_shift) & blue_mask);
SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=XGetPixel(ximage,(int) x,(int) y);
color=(pixel >> red_shift) & red_mask;
if (red_mask != 0)
color=(color*65535UL)/red_mask;
SetPixelRed(q,ScaleShortToQuantum((unsigned short) color));
color=(pixel >> green_shift) & green_mask;
if (green_mask != 0)
color=(color*65535UL)/green_mask;
SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color));
color=(pixel >> blue_shift) & blue_mask;
if (blue_mask != 0)
color=(color*65535UL)/blue_mask;
SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
break;
}
case PseudoClass:
{
/*
Convert X image to PseudoClass packets.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleShortToQuantum(colors[i].red);
image->colormap[i].green=ScaleShortToQuantum(colors[i].green);
image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int)
x,(int) y));
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
break;
}
}
/*
Free image and colormap.
*/
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
|
CWE-369
| 182,865 | 4,063 |
335197007716929309786690441851619569110
| null | null | null |
ImageMagick
|
e3cdce6fe12193f235b8c0ae5efe6880a25eb957
| 1 |
static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define MonoColorType 1
#define RGBColorType 3
char
property[MagickPathExtent];
CINInfo
cin;
const unsigned char
*pixels;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
register Quantum
*q;
size_t
length;
ssize_t
count,
y;
unsigned char
magick[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
File information.
*/
offset=0;
count=ReadBlob(image,4,magick);
offset+=count;
if ((count != 4) ||
((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
memset(&cin,0,sizeof(cin));
image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&
(magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;
cin.file.image_offset=ReadBlobLong(image);
offset+=4;
cin.file.generic_length=ReadBlobLong(image);
offset+=4;
cin.file.industry_length=ReadBlobLong(image);
offset+=4;
cin.file.user_length=ReadBlobLong(image);
offset+=4;
cin.file.file_size=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)
cin.file.version);
(void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));
(void) SetImageProperty(image,"dpx:file.version",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)
cin.file.filename);
(void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));
(void) SetImageProperty(image,"dpx:file.filename",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)
cin.file.create_date);
(void) CopyMagickString(property,cin.file.create_date,
sizeof(cin.file.create_date));
(void) SetImageProperty(image,"dpx:file.create_date",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)
cin.file.create_time);
(void) CopyMagickString(property,cin.file.create_time,
sizeof(cin.file.create_time));
(void) SetImageProperty(image,"dpx:file.create_time",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)
cin.file.reserve);
/*
Image information.
*/
cin.image.orientation=(unsigned char) ReadBlobByte(image);
offset++;
if (cin.image.orientation != (unsigned char) (~0))
(void) FormatImageProperty(image,"dpx:image.orientation","%d",
cin.image.orientation);
switch (cin.image.orientation)
{
default:
case 0: image->orientation=TopLeftOrientation; break;
case 1: image->orientation=TopRightOrientation; break;
case 2: image->orientation=BottomLeftOrientation; break;
case 3: image->orientation=BottomRightOrientation; break;
case 4: image->orientation=LeftTopOrientation; break;
case 5: image->orientation=RightTopOrientation; break;
case 6: image->orientation=LeftBottomOrientation; break;
case 7: image->orientation=RightBottomOrientation; break;
}
cin.image.number_channels=(unsigned char) ReadBlobByte(image);
offset++;
offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
cin.image.reserve1);
for (i=0; i < 8; i++)
{
cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].pixels_per_line=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].lines_per_image=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].min_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].min_quantity=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_quantity=ReadBlobFloat(image);
offset+=4;
}
cin.image.white_point[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)
image->chromaticity.white_point.x=cin.image.white_point[0];
cin.image.white_point[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)
image->chromaticity.white_point.y=cin.image.white_point[1];
cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];
cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];
cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];
cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];
cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];
cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];
offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)
cin.image.label);
(void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));
(void) SetImageProperty(image,"dpx:image.label",property,exception);
offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)
cin.image.reserve);
/*
Image data format information.
*/
cin.data_format.interleave=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.packing=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sign=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sense=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.line_pad=ReadBlobLong(image);
offset+=4;
cin.data_format.channel_pad=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
cin.data_format.reserve);
/*
Image origination information.
*/
cin.origination.x_offset=ReadBlobSignedLong(image);
offset+=4;
if ((size_t) cin.origination.x_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g",
(double) cin.origination.x_offset);
cin.origination.y_offset=(ssize_t) ReadBlobLong(image);
offset+=4;
if ((size_t) cin.origination.y_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g",
(double) cin.origination.y_offset);
offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)
cin.origination.filename);
(void) CopyMagickString(property,cin.origination.filename,
sizeof(cin.origination.filename));
(void) SetImageProperty(image,"dpx:origination.filename",property,exception);
offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
cin.origination.create_date);
(void) CopyMagickString(property,cin.origination.create_date,
sizeof(cin.origination.create_date));
(void) SetImageProperty(image,"dpx:origination.create_date",property,
exception);
offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
cin.origination.create_time);
(void) CopyMagickString(property,cin.origination.create_time,
sizeof(cin.origination.create_time));
(void) SetImageProperty(image,"dpx:origination.create_time",property,
exception);
offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)
cin.origination.device);
(void) CopyMagickString(property,cin.origination.device,
sizeof(cin.origination.device));
(void) SetImageProperty(image,"dpx:origination.device",property,exception);
offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)
cin.origination.model);
(void) CopyMagickString(property,cin.origination.model,
sizeof(cin.origination.model));
(void) SetImageProperty(image,"dpx:origination.model",property,exception);
(void) memset(cin.origination.serial,0,
sizeof(cin.origination.serial));
offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)
cin.origination.serial);
(void) CopyMagickString(property,cin.origination.serial,
sizeof(cin.origination.serial));
(void) SetImageProperty(image,"dpx:origination.serial",property,exception);
cin.origination.x_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.y_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.gamma=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.origination.gamma) != MagickFalse)
image->gamma=cin.origination.gamma;
offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
cin.origination.reserve);
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
int
c;
/*
Image film information.
*/
cin.film.id=ReadBlobByte(image);
offset++;
c=cin.film.id;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id);
cin.film.type=ReadBlobByte(image);
offset++;
c=cin.film.type;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type);
cin.film.offset=ReadBlobByte(image);
offset++;
c=cin.film.offset;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.offset","%d",
cin.film.offset);
cin.film.reserve1=ReadBlobByte(image);
offset++;
cin.film.prefix=ReadBlobLong(image);
offset+=4;
if (cin.film.prefix != ~0UL)
(void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double)
cin.film.prefix);
cin.film.count=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)
cin.film.format);
(void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format));
(void) SetImageProperty(image,"dpx:film.format",property,exception);
cin.film.frame_position=ReadBlobLong(image);
offset+=4;
if (cin.film.frame_position != ~0UL)
(void) FormatImageProperty(image,"dpx:film.frame_position","%.20g",
(double) cin.film.frame_position);
cin.film.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.frame_rate","%g",
cin.film.frame_rate);
offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
cin.film.frame_id);
(void) CopyMagickString(property,cin.film.frame_id,
sizeof(cin.film.frame_id));
(void) SetImageProperty(image,"dpx:film.frame_id",property,exception);
offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
cin.film.slate_info);
(void) CopyMagickString(property,cin.film.slate_info,
sizeof(cin.film.slate_info));
(void) SetImageProperty(image,"dpx:film.slate_info",property,exception);
offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)
cin.film.reserve);
}
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
StringInfo
*profile;
/*
User defined data.
*/
if (cin.file.user_length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
profile=BlobToStringInfo((const unsigned char *) NULL,
cin.file.user_length);
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
offset+=ReadBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) SetImageProfile(image,"dpx:user.data",profile,exception);
profile=DestroyStringInfo(profile);
}
image->depth=cin.image.channel[0].bits_per_pixel;
image->columns=cin.image.channel[0].pixels_per_line;
image->rows=cin.image.channel[0].lines_per_image;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
if (offset < (MagickOffsetType) cin.file.image_offset)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) SetImageBackgroundColor(image,exception);
/*
Convert CIN raster image to pixel packets.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->quantum=32;
quantum_info->pack=MagickFalse;
quantum_type=RGBQuantum;
length=GetQuantumExtent(image,quantum_info,quantum_type);
length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
if (cin.image.number_channels == 1)
{
quantum_type=GrayQuantum;
length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
pixels=(const unsigned char *) ReadBlobStream(image,length,
GetQuantumPixels(quantum_info),&count);
if ((size_t) count != length)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
SetImageColorspace(image,LogColorspace,exception);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
|
CWE-400
| 182,866 | 4,064 |
59197480976158013763578631529515827484
| null | null | null |
libarchive
|
ba641f73f3d758d9032b3f0e5597a9c6e593a505
| 1 |
archive_read_format_zip_cleanup(struct archive_read *a)
{
struct zip *zip;
struct zip_entry *zip_entry, *next_zip_entry;
zip = (struct zip *)(a->format->data);
#ifdef HAVE_ZLIB_H
if (zip->stream_valid)
inflateEnd(&zip->stream);
#endif
#if HAVA_LZMA_H && HAVE_LIBLZMA
if (zip->zipx_lzma_valid) {
lzma_end(&zip->zipx_lzma_stream);
}
#endif
#ifdef HAVE_BZLIB_H
if (zip->bzstream_valid) {
BZ2_bzDecompressEnd(&zip->bzstream);
}
#endif
free(zip->uncompressed_buffer);
if (zip->ppmd8_valid)
__archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
if (zip->zip_entries) {
zip_entry = zip->zip_entries;
while (zip_entry != NULL) {
next_zip_entry = zip_entry->next;
archive_string_free(&zip_entry->rsrcname);
free(zip_entry);
zip_entry = next_zip_entry;
}
}
free(zip->decrypted_buffer);
if (zip->cctx_valid)
archive_decrypto_aes_ctr_release(&zip->cctx);
if (zip->hctx_valid)
archive_hmac_sha1_cleanup(&zip->hctx);
free(zip->iv);
free(zip->erd);
free(zip->v_data);
archive_string_free(&zip->format_name);
free(zip);
(a->format->data) = NULL;
return (ARCHIVE_OK);
}
|
CWE-399
| 182,867 | 4,065 |
281804672906394540236430079284030171732
| null | null | null |
mujs
|
1e5479084bc9852854feb1ba9bf68b52cd127e02
| 1 |
static void ctrycatchfinally(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm, js_Ast *finallystm)
{
int L1, L2, L3;
L1 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the try block */
L2 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the catch block */
cstm(J, F, finallystm); /* inline finally block */
emit(J, F, OP_THROW); /* rethrow exception */
}
label(J, F, L2);
if (F->strict) {
checkfutureword(J, F, catchvar);
if (!strcmp(catchvar->string, "arguments"))
jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode");
if (!strcmp(catchvar->string, "eval"))
jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode");
}
emitline(J, F, catchvar);
emitstring(J, F, OP_CATCH, catchvar->string);
cstm(J, F, catchstm);
emit(J, F, OP_ENDCATCH);
L3 = emitjump(J, F, OP_JUMP); /* skip past the try block to the finally block */
}
label(J, F, L1);
cstm(J, F, trystm);
emit(J, F, OP_ENDTRY);
label(J, F, L3);
cstm(J, F, finallystm);
}
|
CWE-119
| 182,874 | 4,072 |
129287468632431318936669110893135945445
| null | null | null |
mujs
|
da632ca08f240590d2dec786722ed08486ce1be6
| 1 |
static void numtostr(js_State *J, const char *fmt, int w, double n)
{
char buf[32], *e;
sprintf(buf, fmt, w, n);
e = strchr(buf, 'e');
if (e) {
int exp = atoi(e+1);
sprintf(e, "e%+d", exp);
}
js_pushstring(J, buf);
}
|
CWE-119
| 182,876 | 4,074 |
19501154810031546242792994396477046592
| null | null | null |
FFmpeg
|
d227ed5d598340e719eff7156b1aa0a4469e9a6a
| 1 |
static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
additional_code_len, sign, mismatch;
VLC *cur_vlc = &ctx->studio_intra_tab[0];
uint8_t *const scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
uint32_t flc;
const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));
const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
mismatch = 1;
memset(block, 0, 64 * sizeof(int32_t));
if (n < 4) {
cc = 0;
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->intra_matrix;
} else {
cc = (n & 1) + 1;
if (ctx->rgb)
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
else
dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->chroma_intra_matrix;
}
if (dct_dc_size < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n");
return AVERROR_INVALIDDATA;
} else if (dct_dc_size == 0) {
dct_diff = 0;
} else {
dct_diff = get_xbits(&s->gb, dct_dc_size);
if (dct_dc_size > 8) {
if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
return AVERROR_INVALIDDATA;
}
}
s->last_dc[cc] += dct_diff;
if (s->mpeg_quant)
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
else
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
/* TODO: support mpeg_quant for AC coefficients */
block[0] = av_clip(block[0], min, max);
mismatch ^= block[0];
/* AC Coefficients */
while (1) {
group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
if (group < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
return AVERROR_INVALIDDATA;
}
additional_code_len = ac_state_tab[group][0];
cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
if (group == 0) {
/* End of Block */
break;
} else if (group >= 1 && group <= 6) {
/* Zero run length (Table B.47) */
run = 1 << additional_code_len;
if (additional_code_len)
run += get_bits(&s->gb, additional_code_len);
idx += run;
continue;
} else if (group >= 7 && group <= 12) {
/* Zero run length and +/-1 level (Table B.48) */
code = get_bits(&s->gb, additional_code_len);
sign = code & 1;
code >>= 1;
run = (1 << (additional_code_len - 1)) + code;
idx += run;
j = scantable[idx++];
block[j] = sign ? 1 : -1;
} else if (group >= 13 && group <= 20) {
/* Level value (Table B.49) */
j = scantable[idx++];
block[j] = get_xbits(&s->gb, additional_code_len);
} else if (group == 21) {
/* Escape */
j = scantable[idx++];
additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
flc = get_bits(&s->gb, additional_code_len);
if (flc >> (additional_code_len-1))
block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
else
block[j] = flc;
}
block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;
block[j] = av_clip(block[j], min, max);
mismatch ^= block[j];
}
block[63] ^= mismatch & 1;
return 0;
}
|
CWE-125
| 182,877 | 4,075 |
148338294310981682246549181097265882007
| null | null | null |
gpac
|
f36525c5beafb78959c3a07d6622c9028de348da
| 1 |
GF_Err gf_bin128_parse(const char *string, bin128 value)
{
u32 len;
u32 i=0;
if (!strnicmp(string, "0x", 2)) string += 2;
len = (u32) strlen(string);
if (len >= 32) {
u32 j;
for (j=0; j<len; j+=2) {
u32 v;
char szV[5];
while (string[j] && !isalnum(string[j]))
j++;
if (!string[j])
break;
sprintf(szV, "%c%c", string[j], string[j+1]);
sscanf(szV, "%x", &v);
value[i] = v;
i++;
}
}
if (i != 16) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string));
return GF_BAD_PARAM;
}
return GF_OK;
}
|
CWE-119
| 182,880 | 4,077 |
205544941712958350585910821045836329036
| null | null | null |
ImageMagick
|
edc7d3035883ddca8413e4fe7689aa2e579ef04a
| 1 |
MagickExport int LocaleLowercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(tolower_l((int) ((unsigned char) c),c_locale));
#endif
return(tolower((int) ((unsigned char) c)));
}
|
CWE-125
| 182,883 | 4,079 |
293889575556524593651625284131601509407
| null | null | null |
libmysofa
|
d39a171e9c6a1c44dbdf43f9db6c3fbd887e38c1
| 1 |
int treeRead(struct READER *reader, struct DATAOBJECT *data) {
int i, j, err, olen, elements, size, x, y, z, b, e, dy, dz, sx, sy, sz, dzy,
szy;
char *input, *output;
uint8_t node_type, node_level;
uint16_t entries_used;
uint32_t size_of_chunk;
uint32_t filter_mask;
uint64_t address_of_left_sibling, address_of_right_sibling, start[4],
child_pointer, key, store;
char buf[4];
UNUSED(node_level);
UNUSED(address_of_right_sibling);
UNUSED(address_of_left_sibling);
UNUSED(key);
if (data->ds.dimensionality > 3) {
log("TREE dimensions > 3");
return MYSOFA_INVALID_FORMAT;
}
/* read signature */
if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "TREE", 4)) {
log("cannot read signature of TREE\n");
return MYSOFA_INVALID_FORMAT;
} log("%08lX %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf);
node_type = (uint8_t)fgetc(reader->fhd);
node_level = (uint8_t)fgetc(reader->fhd);
entries_used = (uint16_t)readValue(reader, 2);
if(entries_used>0x1000)
return MYSOFA_UNSUPPORTED_FORMAT;
address_of_left_sibling = readValue(reader,
reader->superblock.size_of_offsets);
address_of_right_sibling = readValue(reader,
reader->superblock.size_of_offsets);
elements = 1;
for (j = 0; j < data->ds.dimensionality; j++)
elements *= data->datalayout_chunk[j];
dy = data->datalayout_chunk[1];
dz = data->datalayout_chunk[2];
sx = data->ds.dimension_size[0];
sy = data->ds.dimension_size[1];
sz = data->ds.dimension_size[2];
dzy = dz * dy;
szy = sz * sy;
size = data->datalayout_chunk[data->ds.dimensionality];
log("elements %d size %d\n",elements,size);
if (!(output = malloc(elements * size))) {
return MYSOFA_NO_MEMORY;
}
for (e = 0; e < entries_used * 2; e++) {
if (node_type == 0) {
key = readValue(reader, reader->superblock.size_of_lengths);
} else {
size_of_chunk = (uint32_t)readValue(reader, 4);
filter_mask = (uint32_t)readValue(reader, 4);
if (filter_mask) {
log("TREE all filters must be enabled\n");
free(output);
return MYSOFA_INVALID_FORMAT;
}
for (j = 0; j < data->ds.dimensionality; j++) {
start[j] = readValue(reader, 8);
log("start %d %lu\n",j,start[j]);
}
if (readValue(reader, 8)) {
break;
}
child_pointer = readValue(reader,
reader->superblock.size_of_offsets);
log(" data at %lX len %u\n", child_pointer, size_of_chunk);
/* read data */
store = ftell(reader->fhd);
if (fseek(reader->fhd, child_pointer, SEEK_SET)<0) {
free(output);
return errno;
}
if (!(input = malloc(size_of_chunk))) {
free(output);
return MYSOFA_NO_MEMORY;
}
if (fread(input, 1, size_of_chunk, reader->fhd) != size_of_chunk) {
free(output);
free(input);
return MYSOFA_INVALID_FORMAT;
}
olen = elements * size;
err = gunzip(size_of_chunk, input, &olen, output);
free(input);
log(" gunzip %d %d %d\n",err, olen, elements*size);
if (err || olen != elements * size) {
free(output);
return MYSOFA_INVALID_FORMAT;
}
switch (data->ds.dimensionality) {
case 1:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements + start[0];
if (x < sx) {
j = x * size + b;
((char*)data->data)[j] = output[i];
}
}
break;
case 2:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements;
y = x % dy + start[1];
x = x / dy + start[0];
if (y < sy && x < sx) {
j = ((x * sy + y) * size) + b;
((char*)data->data)[j] = output[i];
}
}
break;
case 3:
for (i = 0; i < olen; i++) {
b = i / elements;
x = i % elements;
z = x % dz + start[2];
y = (x / dz) % dy + start[1];
x = (x / dzy) + start[0];
if (z < sz && y < sy && x < sx) {
j = (x * szy + y * sz + z) * size + b;
((char*)data->data)[j] = output[i];
}
}
break;
default:
log("invalid dim\n");
return MYSOFA_INTERNAL_ERROR;
}
if(fseek(reader->fhd, store, SEEK_SET)<0) {
free(output);
return errno;
}
}
}
free(output);
if(fseek(reader->fhd, 4, SEEK_CUR)<0) /* skip checksum */
return errno;
return MYSOFA_OK;
}
|
CWE-20
| 182,885 | 4,081 |
20763822898396645724687075724141746977
| null | null | null |
domoticz
|
ee70db46f81afa582c96b887b73bcd2a86feda00
| 1 |
void CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep)
{
std::string idx = request::findValue(&req, "idx");
if (idx == "") {
return;
}
std::vector<std::vector<std::string> > result;
result = m_sql.safe_queryBlob("SELECT Image FROM Floorplans WHERE ID=%s", idx.c_str());
if (result.empty())
return;
reply::set_content(&rep, result[0][0].begin(), result[0][0].end());
std::string oname = "floorplan";
if (result[0][0].size() > 10)
{
if (result[0][0][0] == 'P')
oname += ".png";
else if (result[0][0][0] == -1)
oname += ".jpg";
else if (result[0][0][0] == 'B')
oname += ".bmp";
else if (result[0][0][0] == 'G')
oname += ".gif";
}
reply::add_header_attachment(&rep, oname);
}
|
CWE-89
| 182,886 | 4,082 |
126919339259422647630024323951648713830
| null | null | null |
linux
|
355b98553789b646ed97ad801a619ff898471b92
| 1 |
static __net_init int setup_net(struct net *net, struct user_namespace *user_ns)
{
/* Must be called with pernet_ops_rwsem held */
const struct pernet_operations *ops, *saved_ops;
int error = 0;
LIST_HEAD(net_exit_list);
refcount_set(&net->count, 1);
refcount_set(&net->passive, 1);
net->dev_base_seq = 1;
net->user_ns = user_ns;
idr_init(&net->netns_ids);
spin_lock_init(&net->nsid_lock);
mutex_init(&net->ipv4.ra_mutex);
list_for_each_entry(ops, &pernet_list, list) {
error = ops_init(ops, net);
if (error < 0)
goto out_undo;
}
down_write(&net_rwsem);
list_add_tail_rcu(&net->list, &net_namespace_list);
up_write(&net_rwsem);
out:
return error;
out_undo:
/* Walk through the list backwards calling the exit functions
* for the pernet modules whose init functions did not fail.
*/
list_add(&net->exit_list, &net_exit_list);
saved_ops = ops;
list_for_each_entry_continue_reverse(ops, &pernet_list, list)
ops_exit_list(ops, &net_exit_list);
ops = saved_ops;
list_for_each_entry_continue_reverse(ops, &pernet_list, list)
ops_free_list(ops, &net_exit_list);
rcu_barrier();
goto out;
}
|
CWE-200
| 182,887 | 4,083 |
206504535378372664923772470682709030586
| null | null | null |
ImageMagick
|
cb1214c124e1bd61f7dd551b94a794864861592e
| 1 |
static int format8BIM(Image *ifile, Image *ofile)
{
char
temp[MagickPathExtent];
unsigned int
foundOSType;
int
ID,
resCount,
i,
c;
ssize_t
count;
unsigned char
*PString,
*str;
resCount=0;
foundOSType=0; /* found the OSType */
(void) foundOSType;
c=ReadBlobByte(ifile);
while (c != EOF)
{
if (c == '8')
{
unsigned char
buffer[5];
buffer[0]=(unsigned char) c;
for (i=1; i<4; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
buffer[i] = (unsigned char) c;
}
buffer[4]=0;
if (strcmp((const char *)buffer, "8BIM") == 0)
foundOSType=1;
else
continue;
}
else
{
c=ReadBlobByte(ifile);
continue;
}
/*
We found the OSType (8BIM) and now grab the ID, PString, and Size fields.
*/
ID=ReadBlobMSBSignedShort(ifile);
if (ID < 0)
return(-1);
{
unsigned char
plen;
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
plen = (unsigned char) c;
PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+
MagickPathExtent),sizeof(*PString));
if (PString == (unsigned char *) NULL)
return 0;
for (i=0; i<plen; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
PString[i] = (unsigned char) c;
}
PString[ plen ] = 0;
if ((plen & 0x01) == 0)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
}
}
count=(ssize_t) ReadBlobMSBSignedLong(ifile);
if ((count < 0) || (count > GetBlobSize(ifile)))
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
/* make a buffer to hold the data and snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str));
if (str == (unsigned char *) NULL)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return 0;
}
for (i=0; i < (ssize_t) count; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
str[i]=(unsigned char) c;
}
/* we currently skip thumbnails, since it does not make
* any sense preserving them in a real world application
*/
if (ID != THUMBNAIL_ID)
{
/* now finish up by formatting this binary data into
* ASCII equivalent
*/
if (strlen((const char *)PString) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID,
PString);
else
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID);
(void) WriteBlobString(ofile,temp);
if (ID == IPTC_ID)
{
formatString(ofile, "IPTC", 4);
formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count);
}
else
formatString(ofile, (char *)str, (ssize_t) count);
}
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
resCount++;
c=ReadBlobByte(ifile);
}
return resCount;
}
|
CWE-119
| 182,892 | 4,088 |
166827350039151741690507143655227145454
| null | null | null |
libu2f-host
|
e4bb58cc8b6202a421e65f8230217d8ae6e16eb5
| 1 |
init_device (u2fh_devs * devs, struct u2fdevice *dev)
{
unsigned char resp[1024];
unsigned char nonce[8];
if (obtain_nonce(nonce) != 0)
{
return U2FH_TRANSPORT_ERROR;
}
size_t resplen = sizeof (resp);
dev->cid = CID_BROADCAST;
if (u2fh_sendrecv
(devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp,
&resplen) == U2FH_OK)
{
U2FHID_INIT_RESP initresp;
if (resplen > sizeof (initresp))
{
return U2FH_MEMORY_ERROR;
}
memcpy (&initresp, resp, resplen);
dev->cid = initresp.cid;
dev->versionInterface = initresp.versionInterface;
dev->versionMajor = initresp.versionMajor;
dev->versionMinor = initresp.versionMinor;
dev->capFlags = initresp.capFlags;
}
else
{
return U2FH_TRANSPORT_ERROR;
}
return U2FH_OK;
}
|
CWE-119
| 182,893 | 4,089 |
68338259853873011776525382873585754706
| null | null | null |
linux
|
0a1d52994d440e21def1c2174932410b4f2a98a1
| 1 |
int expand_downwards(struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *prev;
int error;
address &= PAGE_MASK;
error = security_mmap_addr(address);
if (error)
return error;
/* Enforce stack_guard_gap */
prev = vma->vm_prev;
/* Check that both stack segments have the same anon_vma? */
if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
if (address - prev->vm_end < stack_guard_gap)
return -ENOMEM;
}
/* We must make sure the anon_vma is allocated. */
if (unlikely(anon_vma_prepare(vma)))
return -ENOMEM;
/*
* vma->vm_start/vm_end cannot change under us because the caller
* is required to hold the mmap_sem in read mode. We need the
* anon_vma lock to serialize against concurrent expand_stacks.
*/
anon_vma_lock_write(vma->anon_vma);
/* Somebody else might have raced and expanded it already */
if (address < vma->vm_start) {
unsigned long size, grow;
size = vma->vm_end - address;
grow = (vma->vm_start - address) >> PAGE_SHIFT;
error = -ENOMEM;
if (grow <= vma->vm_pgoff) {
error = acct_stack_growth(vma, size, grow);
if (!error) {
/*
* vma_gap_update() doesn't support concurrent
* updates, but we only hold a shared mmap_sem
* lock here, so we need to protect against
* concurrent vma expansions.
* anon_vma_lock_write() doesn't help here, as
* we don't guarantee that all growable vmas
* in a mm share the same root anon vma.
* So, we reuse mm->page_table_lock to guard
* against concurrent vma expansions.
*/
spin_lock(&mm->page_table_lock);
if (vma->vm_flags & VM_LOCKED)
mm->locked_vm += grow;
vm_stat_account(mm, vma->vm_flags, grow);
anon_vma_interval_tree_pre_update_vma(vma);
vma->vm_start = address;
vma->vm_pgoff -= grow;
anon_vma_interval_tree_post_update_vma(vma);
vma_gap_update(vma);
spin_unlock(&mm->page_table_lock);
perf_event_mmap(vma);
}
}
}
anon_vma_unlock_write(vma->anon_vma);
khugepaged_enter_vma_merge(vma, vma->vm_flags);
validate_mm(mm);
return error;
}
|
CWE-476
| 182,894 | 4,090 |
170619667088948013348411539521166609565
| null | null | null |
linux
|
c4c07b4d6fa1f11880eab8e076d3d060ef3f55fc
| 1 |
int snmp_helper(void *context, size_t hdrlen, unsigned char tag,
const void *data, size_t datalen)
{
struct snmp_ctx *ctx = (struct snmp_ctx *)context;
__be32 *pdata = (__be32 *)data;
if (*pdata == ctx->from) {
pr_debug("%s: %pI4 to %pI4\n", __func__,
(void *)&ctx->from, (void *)&ctx->to);
if (*ctx->check)
fast_csum(ctx, (unsigned char *)data - ctx->begin);
*pdata = ctx->to;
}
return 1;
}
|
CWE-129
| 182,895 | 4,091 |
105977845795719561431149411308956397231
| null | null | null |
linux
|
c4c07b4d6fa1f11880eab8e076d3d060ef3f55fc
| 1 |
int snmp_version(void *context, size_t hdrlen, unsigned char tag,
const void *data, size_t datalen)
{
if (*(unsigned char *)data > 1)
return -ENOTSUPP;
return 1;
}
|
CWE-129
| 182,896 | 4,092 |
198796159557597090519474353896329087730
| null | null | null |
file
|
2858eaf99f6cc5aae129bcbf1e24ad160240185f
| 1 |
do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags, size_t size, int clazz)
{
#ifdef ELFCORE
int os_style = -1;
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return 1;
*flags |= FLAGS_DID_CORE_STYLE;
*flags |= os_style;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (type == NT_NETBSD_CORE_PROCINFO) {
char sbuf[512];
struct NetBSD_elfcore_procinfo pi;
memset(&pi, 0, sizeof(pi));
memcpy(&pi, nbuf + doff, descsz);
if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
file_printable(sbuf, sizeof(sbuf),
RCAST(char *, pi.cpi_name)),
elf_getu32(swap, (uint32_t)pi.cpi_pid),
elf_getu32(swap, pi.cpi_euid),
elf_getu32(swap, pi.cpi_egid),
elf_getu32(swap, pi.cpi_nlwps),
elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
elf_getu32(swap, pi.cpi_signo),
elf_getu32(swap, pi.cpi_sigcode)) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
}
break;
case OS_STYLE_FREEBSD:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t argoff, pidoff;
if (clazz == ELFCLASS32)
argoff = 4 + 4 + 17;
else
argoff = 4 + 4 + 8 + 17;
if (file_printf(ms, ", from '%.80s'", nbuf + doff +
argoff) == -1)
return 1;
pidoff = argoff + 81 + 2;
if (doff + pidoff + 4 <= size) {
if (file_printf(ms, ", pid=%u",
elf_getu32(swap, *RCAST(uint32_t *, (nbuf +
doff + pidoff)))) == -1)
return 1;
}
*flags |= FLAGS_DID_CORE;
}
break;
default:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; cp < nbuf + size && *cp
&& isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
tryanother:
;
}
}
break;
}
#endif
return 0;
}
|
CWE-125
| 182,899 | 4,095 |
251178396706421595709822463951396974217
| null | null | null |
ImageMagick
|
306c1f0fa5754ca78efd16ab752f0e981d4f6b82
| 1 |
static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
#define CFormat "/Filter [ /%s ]\n"
#define ObjectsPerImage 14
#define ThrowPDFException(exception,message) \
{ \
if (xref != (MagickOffsetType *) NULL) \
xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \
ThrowWriterException((exception),(message)); \
}
DisableMSCWarning(4310)
static const char
XMPProfile[]=
{
"<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n"
" <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n"
" <xap:ModifyDate>%s</xap:ModifyDate>\n"
" <xap:CreateDate>%s</xap:CreateDate>\n"
" <xap:MetadataDate>%s</xap:MetadataDate>\n"
" <xap:CreatorTool>%s</xap:CreatorTool>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
" <dc:format>application/pdf</dc:format>\n"
" <dc:title>\n"
" <rdf:Alt>\n"
" <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n"
" </rdf:Alt>\n"
" </dc:title>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n"
" <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n"
" <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n"
" <pdf:Producer>%s</pdf:Producer>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
" <pdfaid:part>3</pdfaid:part>\n"
" <pdfaid:conformance>B</pdfaid:conformance>\n"
" </rdf:Description>\n"
" </rdf:RDF>\n"
"</x:xmpmeta>\n"
"<?xpacket end=\"w\"?>\n"
},
XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 };
RestoreMSCWarning
char
basename[MagickPathExtent],
buffer[MagickPathExtent],
*escape,
date[MagickPathExtent],
**labels,
page_geometry[MagickPathExtent],
*url;
CompressionType
compression;
const char
*device,
*option,
*value;
const StringInfo
*profile;
double
pointsize;
GeometryInfo
geometry_info;
Image
*next,
*tile_image;
MagickBooleanType
status;
MagickOffsetType
offset,
scene,
*xref;
MagickSizeType
number_pixels;
MagickStatusType
flags;
PointInfo
delta,
resolution,
scale;
RectangleInfo
geometry,
media_info,
page_info;
register const Quantum
*p;
register unsigned char
*q;
register ssize_t
i,
x;
size_t
channels,
imageListLength,
info_id,
length,
object,
pages_id,
root_id,
text_size,
version;
ssize_t
count,
page_count,
y;
struct tm
local_time;
time_t
seconds;
unsigned char
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
/*
Allocate X ref memory.
*/
xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref));
if (xref == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(xref,0,2048UL*sizeof(*xref));
/*
Write Info object.
*/
object=0;
version=3;
if (image_info->compression == JPEG2000Compression)
version=(size_t) MagickMax(version,5);
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
if (next->alpha_trait != UndefinedPixelTrait)
version=(size_t) MagickMax(version,4);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
version=(size_t) MagickMax(version,6);
profile=GetImageProfile(image,"icc");
if (profile != (StringInfo *) NULL)
version=(size_t) MagickMax(version,7);
(void) FormatLocaleString(buffer,MagickPathExtent,"%%PDF-1.%.20g \n",(double)
version);
(void) WriteBlobString(image,buffer);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
{
(void) WriteBlobByte(image,'%');
(void) WriteBlobByte(image,0xe2);
(void) WriteBlobByte(image,0xe3);
(void) WriteBlobByte(image,0xcf);
(void) WriteBlobByte(image,0xd3);
(void) WriteBlobByte(image,'\n');
}
/*
Write Catalog object.
*/
xref[object++]=TellBlob(image);
root_id=object;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (LocaleCompare(image_info->magick,"PDFA") != 0)
(void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n",
(double) object+1);
else
{
(void) FormatLocaleString(buffer,MagickPathExtent,"/Metadata %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n",
(double) object+2);
}
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Type /Catalog");
option=GetImageOption(image_info,"pdf:page-direction");
if ((option != (const char *) NULL) &&
(LocaleCompare(option,"right-to-left") == 0))
(void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n");
(void) WriteBlobString(image,"\n");
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
GetPathComponent(image->filename,BasePath,basename);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
{
char
create_date[MagickPathExtent],
modify_date[MagickPathExtent],
timestamp[MagickPathExtent],
*url,
xmp_profile[MagickPathExtent];
/*
Write XMP object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Subtype /XML\n");
*modify_date='\0';
value=GetImageProperty(image,"date:modify",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(modify_date,value,MagickPathExtent);
*create_date='\0';
value=GetImageProperty(image,"date:create",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(create_date,value,MagickPathExtent);
(void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp);
url=(char *) MagickAuthoritativeURL;
escape=EscapeParenthesis(basename);
i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile,
XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url);
escape=DestroyString(escape);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g\n",
(double) i);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Type /Metadata\n");
(void) WriteBlobString(image,">>\nstream\n");
(void) WriteBlobString(image,xmp_profile);
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
}
/*
Write Pages object.
*/
xref[object++]=TellBlob(image);
pages_id=object;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /Pages\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Kids [ %.20g 0 R ",
(double) object+1);
(void) WriteBlobString(image,buffer);
count=(ssize_t) (pages_id+ObjectsPerImage+1);
page_count=1;
if (image_info->adjoin != MagickFalse)
{
Image
*kid_image;
/*
Predict page object id's.
*/
kid_image=image;
for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage)
{
page_count++;
profile=GetImageProfile(kid_image,"icc");
if (profile != (StringInfo *) NULL)
count+=2;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 R ",(double)
count);
(void) WriteBlobString(image,buffer);
kid_image=GetNextImageInList(kid_image);
}
xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL,
sizeof(*xref));
if (xref == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) WriteBlobString(image,"]\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Count %.20g\n",(double)
page_count);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
scene=0;
imageListLength=GetImageListLength(image);
do
{
MagickBooleanType
has_icc_profile;
profile=GetImageProfile(image,"icc");
has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if ((SetImageMonochrome(image,exception) == MagickFalse) ||
(image->alpha_trait != UndefinedPixelTrait))
compression=RLECompression;
break;
}
#if !defined(MAGICKCORE_JPEG_DELEGATE)
case JPEGCompression:
{
compression=RLECompression;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)",
image->filename);
break;
}
#endif
#if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
case JPEG2000Compression:
{
compression=RLECompression;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)",
image->filename);
break;
}
#endif
#if !defined(MAGICKCORE_ZLIB_DELEGATE)
case ZipCompression:
{
compression=RLECompression;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)",
image->filename);
break;
}
#endif
case LZWCompression:
{
if (LocaleCompare(image_info->magick,"PDFA") == 0)
compression=RLECompression; /* LZW compression is forbidden */
break;
}
case NoCompression:
{
if (LocaleCompare(image_info->magick,"PDFA") == 0)
compression=RLECompression; /* ASCII 85 compression is forbidden */
break;
}
default:
break;
}
if (compression == JPEG2000Compression)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Scale relative to dots-per-inch.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
resolution.x=image->resolution.x;
resolution.y=image->resolution.y;
if ((resolution.x == 0.0) || (resolution.y == 0.0))
{
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image_info->density != (char *) NULL)
{
flags=ParseGeometry(image_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image->units == PixelsPerCentimeterResolution)
{
resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);
resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);
}
SetGeometry(image,&geometry);
(void) FormatLocaleString(page_geometry,MagickPathExtent,"%.20gx%.20g",
(double) image->columns,(double) image->rows);
if (image_info->page != (char *) NULL)
(void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent);
else
if ((image->page.width != 0) && (image->page.height != 0))
(void) FormatLocaleString(page_geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double)
image->page.height,(double) image->page.x,(double) image->page.y);
else
if ((image->gravity != UndefinedGravity) &&
(LocaleCompare(image_info->magick,"PDF") == 0))
(void) CopyMagickString(page_geometry,PSPageGeometry,
MagickPathExtent);
(void) ConcatenateMagickString(page_geometry,">",MagickPathExtent);
(void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
scale.x=(double) (geometry.width*delta.x)/resolution.x;
geometry.width=(size_t) floor(scale.x+0.5);
scale.y=(double) (geometry.height*delta.y)/resolution.y;
geometry.height=(size_t) floor(scale.y+0.5);
(void) ParseAbsoluteGeometry(page_geometry,&media_info);
(void) ParseGravityGeometry(image,page_geometry,&page_info,exception);
if (image->gravity != UndefinedGravity)
{
geometry.x=(-page_info.x);
geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);
}
pointsize=12.0;
if (image_info->pointsize != 0.0)
pointsize=image_info->pointsize;
text_size=0;
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
text_size=(size_t) (MultilineCensus(value)*pointsize+12);
(void) text_size;
/*
Write Page object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /Page\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Parent %.20g 0 R\n",
(double) pages_id);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Resources <<\n");
labels=(char **) NULL;
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
labels=StringToList(value);
if (labels != (char **) NULL)
{
(void) FormatLocaleString(buffer,MagickPathExtent,
"/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double)
object+4);
(void) WriteBlobString(image,buffer);
}
(void) FormatLocaleString(buffer,MagickPathExtent,
"/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double)
object+5);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ProcSet %.20g 0 R >>\n",
(double) object+3);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
72.0*media_info.height/resolution.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
72.0*media_info.height/resolution.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Contents %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Thumb %.20g 0 R\n",
(double) object+(has_icc_profile != MagickFalse ? 10 : 8));
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Contents object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
(void) WriteBlobString(image,"q\n");
if (labels != (char **) NULL)
for (i=0; labels[i] != (char *) NULL; i++)
{
(void) WriteBlobString(image,"BT\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/F%.20g %g Tf\n",
(double) image->scene,pointsize);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g Td\n",
(double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+
12));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"(%s) Tj\n",
labels[i]);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"ET\n");
labels[i]=DestroyString(labels[i]);
}
(void) FormatLocaleString(buffer,MagickPathExtent,
"%g 0 0 %g %.20g %.20g cm\n",scale.x,scale.y,(double) geometry.x,
(double) geometry.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Im%.20g Do\n",(double)
image->scene);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"Q\n");
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write Procset object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
if ((image->storage_class == DirectClass) || (image->colors > 256))
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MagickPathExtent);
else
if ((compression == FaxCompression) || (compression == Group4Compression))
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MagickPathExtent);
else
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MagickPathExtent);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ]\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Font object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (labels != (char **) NULL)
{
(void) WriteBlobString(image,"/Type /Font\n");
(void) WriteBlobString(image,"/Subtype /Type1\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Name /F%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/BaseFont /Helvetica\n");
(void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n");
labels=(char **) RelinquishMagickMemory(labels);
}
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write XObject object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /XObject\n");
(void) WriteBlobString(image,"/Subtype /Image\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Im%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"ASCII85Decode");
break;
}
case JPEGCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case JPEG2000Compression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"FlateDecode");
break;
}
case FaxCompression:
case Group4Compression:
{
(void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
MagickPathExtent);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << "
"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
(double) image->columns,(double) image->rows);
break;
}
default:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double)
image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double)
image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n",
(double) object+2);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression) ?
1 : 8);
(void) WriteBlobString(image,buffer);
if (image->alpha_trait != UndefinedPixelTrait)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"/SMask %.20g 0 R\n",
(double) object+(has_icc_profile != MagickFalse ? 9 : 7));
(void) WriteBlobString(image,buffer);
}
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels)))
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
if ((compression == FaxCompression) || (compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse)))
{
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if (LocaleCompare(CCITTParam,"0") == 0)
{
(void) HuffmanEncodeImage(image_info,image,image,exception);
break;
}
(void) Huffman2DEncodeImage(image_info,image,image,exception);
break;
}
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,image,"jpeg",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p)));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(image,p))));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
}
else
if ((image->storage_class == DirectClass) || (image->colors > 256) ||
(compression == JPEGCompression) ||
(compression == JPEG2000Compression))
switch (compression)
{
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,image,"jpeg",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
length*=image->colorspace == CMYKColorspace ? 4UL : 3UL;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runoffset encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
if (image->colorspace == CMYKColorspace)
*q++=ScaleQuantumToChar(GetPixelBlack(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed DirectColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p)));
Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p)));
Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p)));
if (image->colorspace == CMYKColorspace)
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlack(image,p)));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
else
{
/*
Dump number of colors and colormap.
*/
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
ThrowPDFException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
}
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write Colorspace object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
device="DeviceRGB";
channels=0;
if (image->colorspace == CMYKColorspace)
{
device="DeviceCMYK";
channels=4;
}
else
if ((compression == FaxCompression) ||
(compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse)))
{
device="DeviceGray";
channels=1;
}
else
if ((image->storage_class == DirectClass) ||
(image->colors > 256) || (compression == JPEGCompression) ||
(compression == JPEG2000Compression))
{
device="DeviceRGB";
channels=3;
}
profile=GetImageProfile(image,"icc");
if ((profile == (StringInfo *) NULL) || (channels == 0))
{
if (channels != 0)
(void) FormatLocaleString(buffer,MagickPathExtent,"/%s\n",device);
else
(void) FormatLocaleString(buffer,MagickPathExtent,
"[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors-
1,(double) object+3);
(void) WriteBlobString(image,buffer);
}
else
{
const unsigned char
*p;
/*
Write ICC profile.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"[/ICCBased %.20g 0 R]\n",(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",
(double) object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"<<\n/N %.20g\n"
"/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n"
"stream\n",(double) channels,(double) object+1,device);
(void) WriteBlobString(image,buffer);
offset=TellBlob(image);
Ascii85Initialize(image);
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)
Ascii85Encode(image,(unsigned char) *p++);
Ascii85Flush(image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"endstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",
(double) object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Thumb object.
*/
SetGeometry(image,&geometry);
(void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception);
if (tile_image == (Image *) NULL)
return(MagickFalse);
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"ASCII85Decode");
break;
}
case JPEGCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case JPEG2000Compression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"FlateDecode");
break;
}
case FaxCompression:
case Group4Compression:
{
(void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
MagickPathExtent);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << "
"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
(double) tile_image->columns,(double) tile_image->rows);
break;
}
default:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double)
tile_image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double)
tile_image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n",
(double) object-(has_icc_profile != MagickFalse ? 3 : 1));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression) ?
1 : 8);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows;
if ((compression == FaxCompression) ||
(compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(tile_image,exception) != MagickFalse)))
{
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if (LocaleCompare(CCITTParam,"0") == 0)
{
(void) HuffmanEncodeImage(image_info,image,tile_image,
exception);
break;
}
(void) Huffman2DEncodeImage(image_info,image,tile_image,exception);
break;
}
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,tile_image,"jpeg",
exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,tile_image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(
tile_image,p)));
p+=GetPixelChannels(tile_image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(tile_image,p))));
p+=GetPixelChannels(tile_image);
}
}
Ascii85Flush(image);
break;
}
}
}
else
if ((tile_image->storage_class == DirectClass) ||
(tile_image->colors > 256) || (compression == JPEGCompression) ||
(compression == JPEG2000Compression))
switch (compression)
{
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,tile_image,"jpeg",
exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,tile_image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL;
pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(tile_image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p));
if (tile_image->colorspace == CMYKColorspace)
*q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p));
p+=GetPixelChannels(tile_image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed DirectColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelRed(tile_image,p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelGreen(tile_image,p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlue(tile_image,p)));
if (image->colorspace == CMYKColorspace)
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlack(tile_image,p)));
p+=GetPixelChannels(tile_image);
}
}
Ascii85Flush(image);
break;
}
}
else
{
/*
Dump number of colors and colormap.
*/
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowPDFException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(tile_image,p);
p+=GetPixelChannels(tile_image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,(unsigned char)
GetPixelIndex(tile_image,p));
p+=GetPixelChannels(image);
}
}
Ascii85Flush(image);
break;
}
}
}
tile_image=DestroyImage(tile_image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if ((image->storage_class == DirectClass) || (image->colors > 256) ||
(compression == FaxCompression) || (compression == Group4Compression))
(void) WriteBlobString(image,">>\n");
else
{
/*
Write Colormap object.
*/
if (compression == NoCompression)
(void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
if (compression == NoCompression)
Ascii85Initialize(image);
for (i=0; i < (ssize_t) image->colors; i++)
{
if (compression == NoCompression)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].red)));
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].green)));
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].blue)));
continue;
}
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].red)));
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].green)));
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].blue)));
}
if (compression == NoCompression)
Ascii85Flush(image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write softmask object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (image->alpha_trait == UndefinedPixelTrait)
(void) WriteBlobString(image,">>\n");
else
{
(void) WriteBlobString(image,"/Type /XObject\n");
(void) WriteBlobString(image,"/Subtype /Image\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Ma%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"ASCII85Decode");
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"FlateDecode");
break;
}
default:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",
(double) image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",
(double) image->rows);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/ColorSpace /DeviceGray\n");
(void) FormatLocaleString(buffer,MagickPathExtent,
"/BitsPerComponent %d\n",(compression == FaxCompression) ||
(compression == Group4Compression) ? 1 : 8);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
image=DestroyImage(image);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p)));
p+=GetPixelChannels(image);
}
}
Ascii85Flush(image);
break;
}
}
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
/*
Write Metadata object.
*/
xref[object++]=TellBlob(image);
info_id=object;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (LocaleCompare(image_info->magick,"PDFA") == 0)
(void) FormatLocaleString(buffer,MagickPathExtent,"/Title (%s)\n",
EscapeParenthesis(basename));
else
{
wchar_t
*utf16;
utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length);
if (utf16 != (wchar_t *) NULL)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"/Title (\xfe\xff");
(void) WriteBlobString(image,buffer);
for (i=0; i < (ssize_t) length; i++)
(void) WriteBlobMSBShort(image,(unsigned short) utf16[i]);
(void) FormatLocaleString(buffer,MagickPathExtent,")\n");
utf16=(wchar_t *) RelinquishMagickMemory(utf16);
}
}
(void) WriteBlobString(image,buffer);
seconds=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(&seconds,&local_time);
#else
(void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));
#endif
(void) FormatLocaleString(date,MagickPathExtent,"D:%04d%02d%02d%02d%02d%02d",
local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday,
local_time.tm_hour,local_time.tm_min,local_time.tm_sec);
(void) FormatLocaleString(buffer,MagickPathExtent,"/CreationDate (%s)\n",
date);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ModDate (%s)\n",date);
(void) WriteBlobString(image,buffer);
url=(char *) MagickAuthoritativeURL;
escape=EscapeParenthesis(url);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Producer (%s)\n",escape);
escape=DestroyString(escape);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Xref object.
*/
offset=TellBlob(image)-xref[0]+
(LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10;
(void) WriteBlobString(image,"xref\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"0 %.20g\n",(double)
object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"0000000000 65535 f \n");
for (i=0; i < (ssize_t) object; i++)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%010lu 00000 n \n",
(unsigned long) xref[i]);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"trailer\n");
(void) WriteBlobString(image,"<<\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Size %.20g\n",(double)
object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Info %.20g 0 R\n",(double)
info_id);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Root %.20g 0 R\n",(double)
root_id);
(void) WriteBlobString(image,buffer);
(void) SignatureImage(image,exception);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ID [<%s> <%s>]\n",
GetImageProperty(image,"signature",exception),
GetImageProperty(image,"signature",exception));
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"startxref\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"%%EOF\n");
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
(void) CloseBlob(image);
return(MagickTrue);
}
|
CWE-399
| 182,900 | 4,096 |
40501662541508742073087097760048952108
| null | null | null |
ImageMagick
|
8a43abefb38c5e29138e1c9c515b313363541c06
| 1 |
static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
const CompressionType compression,ExceptionInfo *exception)
{
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
ssize_t
y;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,compression,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
memset(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
|
CWE-399
| 182,901 | 4,097 |
68733002057457945600591779625737653781
| null | null | null |
ImageMagick
|
1e6a3ace073c9ec9c71e439c111d23c6e66cb6ae
| 1 |
static MagickBooleanType DecodeImage(Image *image,unsigned char *luma,
unsigned char *chroma1,unsigned char *chroma2,ExceptionInfo *exception)
{
#define IsSync(sum) ((sum & 0xffffff00UL) == 0xfffffe00UL)
#define PCDGetBits(n) \
{ \
sum=(sum << n) & 0xffffffff; \
bits-=n; \
while (bits <= 24) \
{ \
if (p >= (buffer+0x800)) \
{ \
count=ReadBlob(image,0x800,buffer); \
p=buffer; \
} \
sum|=((unsigned int) (*p) << (24-bits)); \
bits+=8; \
p++; \
} \
}
typedef struct PCDTable
{
unsigned int
length,
sequence;
MagickStatusType
mask;
unsigned char
key;
} PCDTable;
PCDTable
*pcd_table[3];
register ssize_t
i,
j;
register PCDTable
*r;
register unsigned char
*p,
*q;
size_t
bits,
length,
plane,
pcd_length[3],
row,
sum;
ssize_t
count,
quantum;
unsigned char
*buffer;
/*
Initialize Huffman tables.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(luma != (unsigned char *) NULL);
assert(chroma1 != (unsigned char *) NULL);
assert(chroma2 != (unsigned char *) NULL);
buffer=(unsigned char *) AcquireQuantumMemory(0x800,sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
sum=0;
bits=32;
p=buffer+0x800;
for (i=0; i < 3; i++)
{
pcd_table[i]=(PCDTable *) NULL;
pcd_length[i]=0;
}
for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)
{
PCDGetBits(8);
length=(sum & 0xff)+1;
pcd_table[i]=(PCDTable *) AcquireQuantumMemory(length,
sizeof(*pcd_table[i]));
if (pcd_table[i] == (PCDTable *) NULL)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
r=pcd_table[i];
for (j=0; j < (ssize_t) length; j++)
{
PCDGetBits(8);
r->length=(unsigned int) (sum & 0xff)+1;
if (r->length > 16)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
return(MagickFalse);
}
PCDGetBits(16);
r->sequence=(unsigned int) (sum & 0xffff) << 16;
PCDGetBits(8);
r->key=(unsigned char) (sum & 0xff);
r->mask=(~((1U << (32-r->length))-1));
r++;
}
pcd_length[i]=(size_t) length;
}
/*
Search for Sync byte.
*/
for (i=0; i < 1; i++)
PCDGetBits(16);
for (i=0; i < 1; i++)
PCDGetBits(16);
while ((sum & 0x00fff000UL) != 0x00fff000UL)
PCDGetBits(8);
while (IsSync(sum) == 0)
PCDGetBits(1);
/*
Recover the Huffman encoded luminance and chrominance deltas.
*/
count=0;
length=0;
plane=0;
row=0;
q=luma;
for ( ; ; )
{
if (IsSync(sum) != 0)
{
/*
Determine plane and row number.
*/
PCDGetBits(16);
row=((sum >> 9) & 0x1fff);
if (row == image->rows)
break;
PCDGetBits(8);
plane=sum >> 30;
PCDGetBits(16);
switch (plane)
{
case 0:
{
q=luma+row*image->columns;
count=(ssize_t) image->columns;
break;
}
case 2:
{
q=chroma1+(row >> 1)*image->columns;
count=(ssize_t) (image->columns >> 1);
plane--;
break;
}
case 3:
{
q=chroma2+(row >> 1)*image->columns;
count=(ssize_t) (image->columns >> 1);
plane--;
break;
}
default:
{
for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)
pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowBinaryException(CorruptImageError,"CorruptImage",
image->filename);
}
}
length=pcd_length[plane];
continue;
}
/*
Decode luminance or chrominance deltas.
*/
r=pcd_table[plane];
for (i=0; ((i < (ssize_t) length) && ((sum & r->mask) != r->sequence)); i++)
r++;
if ((row > image->rows) || (r == (PCDTable *) NULL))
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename);
while ((sum & 0x00fff000) != 0x00fff000)
PCDGetBits(8);
while (IsSync(sum) == 0)
PCDGetBits(1);
continue;
}
if (r->key < 128)
quantum=(ssize_t) (*q)+r->key;
else
quantum=(ssize_t) (*q)+r->key-256;
*q=(unsigned char) ((quantum < 0) ? 0 : (quantum > 255) ? 255 : quantum);
q++;
PCDGetBits(r->length);
count--;
}
/*
Relinquish resources.
*/
for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)
pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
return(MagickTrue);
}
|
CWE-399
| 182,904 | 4,100 |
319777982927308387176848342419988253826
| null | null | null |
mod_auth_mellon
|
62041428a32de402e0be6ba45fe12df6a83bedb8
| 1 |
int am_check_url(request_rec *r, const char *url)
{
const char *i;
for (i = url; *i; i++) {
if (*i >= 0 && *i < ' ') {
/* Deny all control-characters. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r,
"Control character detected in URL.");
return HTTP_BAD_REQUEST;
}
}
return OK;
}
|
CWE-601
| 182,921 | 4,109 |
82672157991462607258828101379330920583
| null | null | null |
gpac
|
d2371b4b204f0a3c0af51ad4e9b491144dd1225c
| 1 |
GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox);
if (e) {
return e;
}
if (!((GF_DataInformationBox *)s)->dref) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n"));
((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);
}
return GF_OK;
}
|
CWE-400
| 182,931 | 4,118 |
102742711928030090978347639185680853176
| null | null | null |
openjpeg
|
2e5ab1d9987831c981ff05862e8ccf1381ed58ea
| 1 |
void color_apply_icc_profile(opj_image_t *image)
{
cmsHPROFILE in_prof, out_prof;
cmsHTRANSFORM transform;
cmsColorSpaceSignature in_space, out_space;
cmsUInt32Number intent, in_type, out_type;
int *r, *g, *b;
size_t nr_samples, i, max, max_w, max_h;
int prec, ok = 0;
OPJ_COLOR_SPACE new_space;
in_prof = cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);
#ifdef DEBUG_PROFILE
FILE *icm = fopen("debug.icm", "wb");
fwrite(image->icc_profile_buf, 1, image->icc_profile_len, icm);
fclose(icm);
#endif
if (in_prof == NULL) {
return;
}
in_space = cmsGetPCS(in_prof);
out_space = cmsGetColorSpace(in_prof);
intent = cmsGetHeaderRenderingIntent(in_prof);
max_w = image->comps[0].w;
max_h = image->comps[0].h;
prec = (int)image->comps[0].prec;
if (out_space == cmsSigRgbData) { /* enumCS 16 */
unsigned int i, nr_comp = image->numcomps;
if (nr_comp > 4) {
nr_comp = 4;
}
for (i = 1; i < nr_comp; ++i) { /* AFL test */
if (image->comps[0].dx != image->comps[i].dx) {
break;
}
if (image->comps[0].dy != image->comps[i].dy) {
break;
}
if (image->comps[0].prec != image->comps[i].prec) {
break;
}
if (image->comps[0].sgnd != image->comps[i].sgnd) {
break;
}
}
if (i != nr_comp) {
cmsCloseProfile(in_prof);
return;
}
if (prec <= 8) {
in_type = TYPE_RGB_8;
out_type = TYPE_RGB_8;
} else {
in_type = TYPE_RGB_16;
out_type = TYPE_RGB_16;
}
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else if (out_space == cmsSigGrayData) { /* enumCS 17 */
in_type = TYPE_GRAY_8;
out_type = TYPE_RGB_8;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else if (out_space == cmsSigYCbCrData) { /* enumCS 18 */
in_type = TYPE_YCbCr_16;
out_type = TYPE_RGB_16;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else {
#ifdef DEBUG_PROFILE
fprintf(stderr, "%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "
"output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n",
__FILE__, __LINE__, out_space,
(out_space >> 24) & 0xff, (out_space >> 16) & 0xff,
(out_space >> 8) & 0xff, out_space & 0xff);
#endif
cmsCloseProfile(in_prof);
return;
}
if (out_prof == NULL) {
cmsCloseProfile(in_prof);
return;
}
#ifdef DEBUG_PROFILE
fprintf(stderr,
"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)"
"\n\tprofile: in(%p) out(%p)\n", __FILE__, __LINE__, image->numcomps, prec,
max_w, max_h, (void*)in_prof, (void*)out_prof);
fprintf(stderr, "\trender_intent (%u)\n\t"
"color_space: in(%#x)(%c%c%c%c) out:(%#x)(%c%c%c%c)\n\t"
" type: in(%u) out:(%u)\n",
intent,
in_space,
(in_space >> 24) & 0xff, (in_space >> 16) & 0xff,
(in_space >> 8) & 0xff, in_space & 0xff,
out_space,
(out_space >> 24) & 0xff, (out_space >> 16) & 0xff,
(out_space >> 8) & 0xff, out_space & 0xff,
in_type, out_type
);
#else
(void)prec;
(void)in_space;
#endif /* DEBUG_PROFILE */
transform = cmsCreateTransform(in_prof, in_type, out_prof, out_type, intent, 0);
#ifdef OPJ_HAVE_LIBLCMS2
/* Possible for: LCMS_VERSION >= 2000 :*/
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if (transform == NULL) {
#ifdef DEBUG_PROFILE
fprintf(stderr, "%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. "
"ICC Profile ignored.\n", __FILE__, __LINE__);
#endif
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
return;
}
if (image->numcomps > 2) { /* RGB, RGBA */
if (prec <= 8) {
unsigned char *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned char));
in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
if (inbuf == NULL || outbuf == NULL) {
goto fails0;
}
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned char) * r++;
*in++ = (unsigned char) * g++;
*in++ = (unsigned char) * b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
ok = 1;
fails0:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
} else { /* prec > 8 */
unsigned short *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned short));
in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
if (inbuf == NULL || outbuf == NULL) {
goto fails1;
}
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U ; i < max; ++i) {
*in++ = (unsigned short) * r++;
*in++ = (unsigned short) * g++;
*in++ = (unsigned short) * b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
ok = 1;
fails1:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
}
} else { /* image->numcomps <= 2 : GRAY, GRAYA */
if (prec <= 8) {
unsigned char *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned char));
in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {
goto fails2;
}
new_comps = (opj_image_comp_t*)realloc(image->comps,
(image->numcomps + 2) * sizeof(opj_image_comp_t));
if (new_comps == NULL) {
goto fails2;
}
image->comps = new_comps;
if (image->numcomps == 2) {
image->comps[3] = image->comps[1];
}
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned char) * r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
r = g = b = NULL;
ok = 1;
fails2:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
opj_image_data_free(g);
opj_image_data_free(b);
} else { /* prec > 8 */
unsigned short *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned short));
in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {
goto fails3;
}
new_comps = (opj_image_comp_t*)realloc(image->comps,
(image->numcomps + 2) * sizeof(opj_image_comp_t));
if (new_comps == NULL) {
goto fails3;
}
image->comps = new_comps;
if (image->numcomps == 2) {
image->comps[3] = image->comps[1];
}
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned short) * r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
r = g = b = NULL;
ok = 1;
fails3:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
opj_image_data_free(g);
opj_image_data_free(b);
}
}/* if(image->numcomps > 2) */
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if (ok) {
image->color_space = new_space;
}
}/* color_apply_icc_profile() */
|
CWE-119
| 182,932 | 4,119 |
105259506362981863350294968544928811288
| null | null | null |
linux
|
7fafcfdf6377b18b2a726ea554d6e593ba44349f
| 1 |
static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_midi *midi = func_to_midi(f);
unsigned i;
int err;
/* we only set alt for MIDIStreaming interface */
if (intf != midi->ms_id)
return 0;
err = f_midi_start_ep(midi, f, midi->in_ep);
if (err)
return err;
err = f_midi_start_ep(midi, f, midi->out_ep);
if (err)
return err;
/* pre-allocate write usb requests to use on f_midi_transmit. */
while (kfifo_avail(&midi->in_req_fifo)) {
struct usb_request *req =
midi_alloc_ep_req(midi->in_ep, midi->buflen);
if (req == NULL)
return -ENOMEM;
req->length = 0;
req->complete = f_midi_complete;
kfifo_put(&midi->in_req_fifo, req);
}
/* allocate a bunch of read buffers and queue them all at once. */
for (i = 0; i < midi->qlen && err == 0; i++) {
struct usb_request *req =
midi_alloc_ep_req(midi->out_ep, midi->buflen);
if (req == NULL)
return -ENOMEM;
req->complete = f_midi_complete;
err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);
if (err) {
ERROR(midi, "%s: couldn't enqueue request: %d\n",
midi->out_ep->name, err);
free_ep_req(midi->out_ep, req);
return err;
}
}
return 0;
}
|
CWE-415
| 182,933 | 4,120 |
319178464914382525930114595393487770130
| null | null | null |
linux
|
54648cf1ec2d7f4b6a71767799c45676a138ca24
| 1 |
int blk_init_allocated_queue(struct request_queue *q)
{
WARN_ON_ONCE(q->mq_ops);
q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, q->cmd_size);
if (!q->fq)
return -ENOMEM;
if (q->init_rq_fn && q->init_rq_fn(q, q->fq->flush_rq, GFP_KERNEL))
goto out_free_flush_queue;
if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
goto out_exit_flush_rq;
INIT_WORK(&q->timeout_work, blk_timeout_work);
q->queue_flags |= QUEUE_FLAG_DEFAULT;
/*
* This also sets hw/phys segments, boundary and size
*/
blk_queue_make_request(q, blk_queue_bio);
q->sg_reserved_size = INT_MAX;
if (elevator_init(q))
goto out_exit_flush_rq;
return 0;
out_exit_flush_rq:
if (q->exit_rq_fn)
q->exit_rq_fn(q, q->fq->flush_rq);
out_free_flush_queue:
blk_free_flush_queue(q->fq);
return -ENOMEM;
}
|
CWE-416
| 182,934 | 4,121 |
302121427349834941479572744251235917829
| null | null | null |
linux
|
0625b4ba1a5d4703c7fb01c497bd6c156908af00
| 1 |
static int create_qp_common(struct mlx5_ib_dev *dev, struct ib_pd *pd,
struct ib_qp_init_attr *init_attr,
struct ib_udata *udata, struct mlx5_ib_qp *qp)
{
struct mlx5_ib_resources *devr = &dev->devr;
int inlen = MLX5_ST_SZ_BYTES(create_qp_in);
struct mlx5_core_dev *mdev = dev->mdev;
struct mlx5_ib_create_qp_resp resp;
struct mlx5_ib_cq *send_cq;
struct mlx5_ib_cq *recv_cq;
unsigned long flags;
u32 uidx = MLX5_IB_DEFAULT_UIDX;
struct mlx5_ib_create_qp ucmd;
struct mlx5_ib_qp_base *base;
int mlx5_st;
void *qpc;
u32 *in;
int err;
mutex_init(&qp->mutex);
spin_lock_init(&qp->sq.lock);
spin_lock_init(&qp->rq.lock);
mlx5_st = to_mlx5_st(init_attr->qp_type);
if (mlx5_st < 0)
return -EINVAL;
if (init_attr->rwq_ind_tbl) {
if (!udata)
return -ENOSYS;
err = create_rss_raw_qp_tir(dev, qp, pd, init_attr, udata);
return err;
}
if (init_attr->create_flags & IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK) {
if (!MLX5_CAP_GEN(mdev, block_lb_mc)) {
mlx5_ib_dbg(dev, "block multicast loopback isn't supported\n");
return -EINVAL;
} else {
qp->flags |= MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK;
}
}
if (init_attr->create_flags &
(IB_QP_CREATE_CROSS_CHANNEL |
IB_QP_CREATE_MANAGED_SEND |
IB_QP_CREATE_MANAGED_RECV)) {
if (!MLX5_CAP_GEN(mdev, cd)) {
mlx5_ib_dbg(dev, "cross-channel isn't supported\n");
return -EINVAL;
}
if (init_attr->create_flags & IB_QP_CREATE_CROSS_CHANNEL)
qp->flags |= MLX5_IB_QP_CROSS_CHANNEL;
if (init_attr->create_flags & IB_QP_CREATE_MANAGED_SEND)
qp->flags |= MLX5_IB_QP_MANAGED_SEND;
if (init_attr->create_flags & IB_QP_CREATE_MANAGED_RECV)
qp->flags |= MLX5_IB_QP_MANAGED_RECV;
}
if (init_attr->qp_type == IB_QPT_UD &&
(init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO))
if (!MLX5_CAP_GEN(mdev, ipoib_basic_offloads)) {
mlx5_ib_dbg(dev, "ipoib UD lso qp isn't supported\n");
return -EOPNOTSUPP;
}
if (init_attr->create_flags & IB_QP_CREATE_SCATTER_FCS) {
if (init_attr->qp_type != IB_QPT_RAW_PACKET) {
mlx5_ib_dbg(dev, "Scatter FCS is supported only for Raw Packet QPs");
return -EOPNOTSUPP;
}
if (!MLX5_CAP_GEN(dev->mdev, eth_net_offloads) ||
!MLX5_CAP_ETH(dev->mdev, scatter_fcs)) {
mlx5_ib_dbg(dev, "Scatter FCS isn't supported\n");
return -EOPNOTSUPP;
}
qp->flags |= MLX5_IB_QP_CAP_SCATTER_FCS;
}
if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR)
qp->sq_signal_bits = MLX5_WQE_CTRL_CQ_UPDATE;
if (init_attr->create_flags & IB_QP_CREATE_CVLAN_STRIPPING) {
if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) &&
MLX5_CAP_ETH(dev->mdev, vlan_cap)) ||
(init_attr->qp_type != IB_QPT_RAW_PACKET))
return -EOPNOTSUPP;
qp->flags |= MLX5_IB_QP_CVLAN_STRIPPING;
}
if (pd && pd->uobject) {
if (ib_copy_from_udata(&ucmd, udata, sizeof(ucmd))) {
mlx5_ib_dbg(dev, "copy failed\n");
return -EFAULT;
}
err = get_qp_user_index(to_mucontext(pd->uobject->context),
&ucmd, udata->inlen, &uidx);
if (err)
return err;
qp->wq_sig = !!(ucmd.flags & MLX5_QP_FLAG_SIGNATURE);
qp->scat_cqe = !!(ucmd.flags & MLX5_QP_FLAG_SCATTER_CQE);
if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) {
if (init_attr->qp_type != IB_QPT_RAW_PACKET ||
!tunnel_offload_supported(mdev)) {
mlx5_ib_dbg(dev, "Tunnel offload isn't supported\n");
return -EOPNOTSUPP;
}
qp->tunnel_offload_en = true;
}
if (init_attr->create_flags & IB_QP_CREATE_SOURCE_QPN) {
if (init_attr->qp_type != IB_QPT_UD ||
(MLX5_CAP_GEN(dev->mdev, port_type) !=
MLX5_CAP_PORT_TYPE_IB) ||
!mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_BYPASS)) {
mlx5_ib_dbg(dev, "Source QP option isn't supported\n");
return -EOPNOTSUPP;
}
qp->flags |= MLX5_IB_QP_UNDERLAY;
qp->underlay_qpn = init_attr->source_qpn;
}
} else {
qp->wq_sig = !!wq_signature;
}
base = (init_attr->qp_type == IB_QPT_RAW_PACKET ||
qp->flags & MLX5_IB_QP_UNDERLAY) ?
&qp->raw_packet_qp.rq.base :
&qp->trans_qp.base;
qp->has_rq = qp_has_rq(init_attr);
err = set_rq_size(dev, &init_attr->cap, qp->has_rq,
qp, (pd && pd->uobject) ? &ucmd : NULL);
if (err) {
mlx5_ib_dbg(dev, "err %d\n", err);
return err;
}
if (pd) {
if (pd->uobject) {
__u32 max_wqes =
1 << MLX5_CAP_GEN(mdev, log_max_qp_sz);
mlx5_ib_dbg(dev, "requested sq_wqe_count (%d)\n", ucmd.sq_wqe_count);
if (ucmd.rq_wqe_shift != qp->rq.wqe_shift ||
ucmd.rq_wqe_count != qp->rq.wqe_cnt) {
mlx5_ib_dbg(dev, "invalid rq params\n");
return -EINVAL;
}
if (ucmd.sq_wqe_count > max_wqes) {
mlx5_ib_dbg(dev, "requested sq_wqe_count (%d) > max allowed (%d)\n",
ucmd.sq_wqe_count, max_wqes);
return -EINVAL;
}
if (init_attr->create_flags &
mlx5_ib_create_qp_sqpn_qp1()) {
mlx5_ib_dbg(dev, "user-space is not allowed to create UD QPs spoofing as QP1\n");
return -EINVAL;
}
err = create_user_qp(dev, pd, qp, udata, init_attr, &in,
&resp, &inlen, base);
if (err)
mlx5_ib_dbg(dev, "err %d\n", err);
} else {
err = create_kernel_qp(dev, init_attr, qp, &in, &inlen,
base);
if (err)
mlx5_ib_dbg(dev, "err %d\n", err);
}
if (err)
return err;
} else {
in = kvzalloc(inlen, GFP_KERNEL);
if (!in)
return -ENOMEM;
qp->create_type = MLX5_QP_EMPTY;
}
if (is_sqp(init_attr->qp_type))
qp->port = init_attr->port_num;
qpc = MLX5_ADDR_OF(create_qp_in, in, qpc);
MLX5_SET(qpc, qpc, st, mlx5_st);
MLX5_SET(qpc, qpc, pm_state, MLX5_QP_PM_MIGRATED);
if (init_attr->qp_type != MLX5_IB_QPT_REG_UMR)
MLX5_SET(qpc, qpc, pd, to_mpd(pd ? pd : devr->p0)->pdn);
else
MLX5_SET(qpc, qpc, latency_sensitive, 1);
if (qp->wq_sig)
MLX5_SET(qpc, qpc, wq_signature, 1);
if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK)
MLX5_SET(qpc, qpc, block_lb_mc, 1);
if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL)
MLX5_SET(qpc, qpc, cd_master, 1);
if (qp->flags & MLX5_IB_QP_MANAGED_SEND)
MLX5_SET(qpc, qpc, cd_slave_send, 1);
if (qp->flags & MLX5_IB_QP_MANAGED_RECV)
MLX5_SET(qpc, qpc, cd_slave_receive, 1);
if (qp->scat_cqe && is_connected(init_attr->qp_type)) {
int rcqe_sz;
int scqe_sz;
rcqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->recv_cq);
scqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->send_cq);
if (rcqe_sz == 128)
MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA64_CQE);
else
MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA32_CQE);
if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) {
if (scqe_sz == 128)
MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA64_CQE);
else
MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA32_CQE);
}
}
if (qp->rq.wqe_cnt) {
MLX5_SET(qpc, qpc, log_rq_stride, qp->rq.wqe_shift - 4);
MLX5_SET(qpc, qpc, log_rq_size, ilog2(qp->rq.wqe_cnt));
}
MLX5_SET(qpc, qpc, rq_type, get_rx_type(qp, init_attr));
if (qp->sq.wqe_cnt) {
MLX5_SET(qpc, qpc, log_sq_size, ilog2(qp->sq.wqe_cnt));
} else {
MLX5_SET(qpc, qpc, no_sq, 1);
if (init_attr->srq &&
init_attr->srq->srq_type == IB_SRQT_TM)
MLX5_SET(qpc, qpc, offload_type,
MLX5_QPC_OFFLOAD_TYPE_RNDV);
}
/* Set default resources */
switch (init_attr->qp_type) {
case IB_QPT_XRC_TGT:
MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn);
MLX5_SET(qpc, qpc, cqn_snd, to_mcq(devr->c0)->mcq.cqn);
MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn);
MLX5_SET(qpc, qpc, xrcd, to_mxrcd(init_attr->xrcd)->xrcdn);
break;
case IB_QPT_XRC_INI:
MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn);
MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn);
MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn);
break;
default:
if (init_attr->srq) {
MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x0)->xrcdn);
MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(init_attr->srq)->msrq.srqn);
} else {
MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn);
MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s1)->msrq.srqn);
}
}
if (init_attr->send_cq)
MLX5_SET(qpc, qpc, cqn_snd, to_mcq(init_attr->send_cq)->mcq.cqn);
if (init_attr->recv_cq)
MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(init_attr->recv_cq)->mcq.cqn);
MLX5_SET64(qpc, qpc, dbr_addr, qp->db.dma);
/* 0xffffff means we ask to work with cqe version 0 */
if (MLX5_CAP_GEN(mdev, cqe_version) == MLX5_CQE_VERSION_V1)
MLX5_SET(qpc, qpc, user_index, uidx);
/* we use IB_QP_CREATE_IPOIB_UD_LSO to indicates ipoib qp */
if (init_attr->qp_type == IB_QPT_UD &&
(init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) {
MLX5_SET(qpc, qpc, ulp_stateless_offload_mode, 1);
qp->flags |= MLX5_IB_QP_LSO;
}
if (init_attr->create_flags & IB_QP_CREATE_PCI_WRITE_END_PADDING) {
if (!MLX5_CAP_GEN(dev->mdev, end_pad)) {
mlx5_ib_dbg(dev, "scatter end padding is not supported\n");
err = -EOPNOTSUPP;
goto err;
} else if (init_attr->qp_type != IB_QPT_RAW_PACKET) {
MLX5_SET(qpc, qpc, end_padding_mode,
MLX5_WQ_END_PAD_MODE_ALIGN);
} else {
qp->flags |= MLX5_IB_QP_PCI_WRITE_END_PADDING;
}
}
if (inlen < 0) {
err = -EINVAL;
goto err;
}
if (init_attr->qp_type == IB_QPT_RAW_PACKET ||
qp->flags & MLX5_IB_QP_UNDERLAY) {
qp->raw_packet_qp.sq.ubuffer.buf_addr = ucmd.sq_buf_addr;
raw_packet_qp_copy_info(qp, &qp->raw_packet_qp);
err = create_raw_packet_qp(dev, qp, in, inlen, pd);
} else {
err = mlx5_core_create_qp(dev->mdev, &base->mqp, in, inlen);
}
if (err) {
mlx5_ib_dbg(dev, "create qp failed\n");
goto err_create;
}
kvfree(in);
base->container_mibqp = qp;
base->mqp.event = mlx5_ib_qp_event;
get_cqs(init_attr->qp_type, init_attr->send_cq, init_attr->recv_cq,
&send_cq, &recv_cq);
spin_lock_irqsave(&dev->reset_flow_resource_lock, flags);
mlx5_ib_lock_cqs(send_cq, recv_cq);
/* Maintain device to QPs access, needed for further handling via reset
* flow
*/
list_add_tail(&qp->qps_list, &dev->qp_list);
/* Maintain CQ to QPs access, needed for further handling via reset flow
*/
if (send_cq)
list_add_tail(&qp->cq_send_list, &send_cq->list_send_qp);
if (recv_cq)
list_add_tail(&qp->cq_recv_list, &recv_cq->list_recv_qp);
mlx5_ib_unlock_cqs(send_cq, recv_cq);
spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags);
return 0;
err_create:
if (qp->create_type == MLX5_QP_USER)
destroy_qp_user(dev, pd, qp, base);
else if (qp->create_type == MLX5_QP_KERNEL)
destroy_qp_kernel(dev, qp);
err:
kvfree(in);
return err;
}
|
CWE-119
| 182,935 | 4,122 |
248861397606415771660337369758545165893
| null | null | null |
openjpeg
|
c58df149900df862806d0e892859b41115875845
| 1 |
static void opj_get_encoding_parameters(const opj_image_t *p_image,
const opj_cp_t *p_cp,
OPJ_UINT32 p_tileno,
OPJ_INT32 * p_tx0,
OPJ_INT32 * p_tx1,
OPJ_INT32 * p_ty0,
OPJ_INT32 * p_ty1,
OPJ_UINT32 * p_dx_min,
OPJ_UINT32 * p_dy_min,
OPJ_UINT32 * p_max_prec,
OPJ_UINT32 * p_max_res)
{
/* loop */
OPJ_UINT32 compno, resno;
/* pointers */
const opj_tcp_t *l_tcp = 00;
const opj_tccp_t * l_tccp = 00;
const opj_image_comp_t * l_img_comp = 00;
/* position in x and y of tile */
OPJ_UINT32 p, q;
/* preconditions */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tileno < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps [p_tileno];
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
/* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */
p = p_tileno % p_cp->tw;
q = p_tileno / p_cp->tw;
/* find extent of tile */
*p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx),
(OPJ_INT32)p_image->x0);
*p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx),
(OPJ_INT32)p_image->x1);
*p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy),
(OPJ_INT32)p_image->y0);
*p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy),
(OPJ_INT32)p_image->y1);
/* max precision is 0 (can only grow) */
*p_max_prec = 0;
*p_max_res = 0;
/* take the largest value for dx_min and dy_min */
*p_dx_min = 0x7fffffff;
*p_dy_min = 0x7fffffff;
for (compno = 0; compno < p_image->numcomps; ++compno) {
/* arithmetic variables to calculate */
OPJ_UINT32 l_level_no;
OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
OPJ_INT32 l_px0, l_py0, l_px1, py1;
OPJ_UINT32 l_pdx, l_pdy;
OPJ_UINT32 l_pw, l_ph;
OPJ_UINT32 l_product;
OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);
if (l_tccp->numresolutions > *p_max_res) {
*p_max_res = l_tccp->numresolutions;
}
/* use custom size for precincts */
for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
OPJ_UINT32 l_dx, l_dy;
/* precinct width and height */
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno));
l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno));
/* take the minimum size for dx for each comp and resolution */
*p_dx_min = opj_uint_min(*p_dx_min, l_dx);
*p_dy_min = opj_uint_min(*p_dy_min, l_dy);
/* various calculations of extents */
l_level_no = l_tccp->numresolutions - 1 - resno;
l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);
l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;
py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;
l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy);
l_product = l_pw * l_ph;
/* update precision */
if (l_product > *p_max_prec) {
*p_max_prec = l_product;
}
}
++l_img_comp;
++l_tccp;
}
}
|
CWE-190
| 182,938 | 4,124 |
296815004190301402876373173896009691531
| null | null | null |
openjpeg
|
c277159986c80142180fbe5efb256bbf3bdf3edc
| 1 |
static opj_bool pi_next_cprl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
|
CWE-20
| 182,939 | 4,125 |
85538911631696436460516893403758082234
| null | null | null |
openjpeg
|
c277159986c80142180fbe5efb256bbf3bdf3edc
| 1 |
static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1;
pi->resno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if (!pi->tp_on) {
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
return OPJ_FALSE;
}
|
CWE-20
| 182,940 | 4,126 |
152272228207417513535793022438218291661
| null | null | null |
openjpeg
|
c277159986c80142180fbe5efb256bbf3bdf3edc
| 1 |
static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
|
CWE-20
| 182,941 | 4,127 |
95796440332548904709677290202295606870
| null | null | null |
openjpeg
|
c277159986c80142180fbe5efb256bbf3bdf3edc
| 1 |
static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if (!pi->tp_on) {
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
return OPJ_FALSE;
}
|
CWE-20
| 182,942 | 4,128 |
223188624698480937160097928771864488414
| null | null | null |
openjpeg
|
c277159986c80142180fbe5efb256bbf3bdf3edc
| 1 |
static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
|
CWE-20
| 182,943 | 4,129 |
80601494770304421913970303638663964635
| null | null | null |
openjpeg
|
c5bd64ea146162967c29bd2af0cbb845ba3eaaaf
| 1 |
static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
|
CWE-369
| 182,945 | 4,130 |
305172269991258651209618589071226407822
| null | null | null |
openjpeg
|
c5bd64ea146162967c29bd2af0cbb845ba3eaaaf
| 1 |
static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
|
CWE-369
| 182,946 | 4,131 |
146244999549307642058262133079698547599
| null | null | null |
libexpat
|
11f8838bf99ea0a6f0b76f9760c43704d00c4ff6
| 1 |
setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name;
for (name = elementType->name; *name; name++) {
if (*name == XML_T(ASCII_COLON)) {
PREFIX *prefix;
const XML_Char *s;
for (s = elementType->name; s != name; s++) {
if (!poolAppendChar(&dtd->pool, *s))
return 0;
}
if (!poolAppendChar(&dtd->pool, XML_T('\0')))
return 0;
prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
sizeof(PREFIX));
if (!prefix)
return 0;
if (prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
elementType->prefix = prefix;
}
}
return 1;
}
|
CWE-611
| 182,947 | 4,132 |
149797917410026082782148287670167196283
| null | null | null |
linux
|
b90cd6f2b905905fb42671009dc0e27c310a16ae
| 1 |
static void smp_task_done(struct sas_task *task)
{
if (!del_timer(&task->slow_task->timer))
return;
complete(&task->slow_task->completion);
}
|
CWE-416
| 182,954 | 4,137 |
29609062973361010006381958723218404121
| null | null | null |
linux
|
b90cd6f2b905905fb42671009dc0e27c310a16ae
| 1 |
static void smp_task_timedout(struct timer_list *t)
{
struct sas_task_slow *slow = from_timer(slow, t, timer);
struct sas_task *task = slow->task;
unsigned long flags;
spin_lock_irqsave(&task->task_state_lock, flags);
if (!(task->task_state_flags & SAS_TASK_STATE_DONE))
task->task_state_flags |= SAS_TASK_STATE_ABORTED;
spin_unlock_irqrestore(&task->task_state_lock, flags);
complete(&task->slow_task->completion);
}
|
CWE-416
| 182,955 | 4,138 |
300277114529588775125867747341691755992
| null | null | null |
linux
|
c40f7d74c741a907cfaeb73a7697081881c497d0
| 1 |
static void update_blocked_averages(int cpu)
{
struct rq *rq = cpu_rq(cpu);
struct cfs_rq *cfs_rq, *pos;
const struct sched_class *curr_class;
struct rq_flags rf;
bool done = true;
rq_lock_irqsave(rq, &rf);
update_rq_clock(rq);
/*
* Iterates the task_group tree in a bottom up fashion, see
* list_add_leaf_cfs_rq() for details.
*/
for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
struct sched_entity *se;
/* throttled entities do not contribute to load */
if (throttled_hierarchy(cfs_rq))
continue;
if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq))
update_tg_load_avg(cfs_rq, 0);
/* Propagate pending load changes to the parent, if any: */
se = cfs_rq->tg->se[cpu];
if (se && !skip_blocked_update(se))
update_load_avg(cfs_rq_of(se), se, 0);
/*
* There can be a lot of idle CPU cgroups. Don't let fully
* decayed cfs_rqs linger on the list.
*/
if (cfs_rq_is_decayed(cfs_rq))
list_del_leaf_cfs_rq(cfs_rq);
/* Don't need periodic decay once load/util_avg are null */
if (cfs_rq_has_blocked(cfs_rq))
done = false;
}
curr_class = rq->curr->sched_class;
update_rt_rq_load_avg(rq_clock_task(rq), rq, curr_class == &rt_sched_class);
update_dl_rq_load_avg(rq_clock_task(rq), rq, curr_class == &dl_sched_class);
update_irq_load_avg(rq, 0);
/* Don't need periodic decay once load/util_avg are null */
if (others_have_blocked(rq))
done = false;
#ifdef CONFIG_NO_HZ_COMMON
rq->last_blocked_load_update_tick = jiffies;
if (done)
rq->has_blocked_load = 0;
#endif
rq_unlock_irqrestore(rq, &rf);
}
|
CWE-400
| 182,958 | 4,141 |
242733069005675974880802073631378918720
| null | null | null |
gpac
|
1c449a34fe0b50aaffb881bfb9d7c5ab0bb18cdd
| 1 |
int mp4client_main(int argc, char **argv)
{
char c;
const char *str;
int ret_val = 0;
u32 i, times[100], nb_times, dump_mode;
u32 simulation_time_in_ms = 0;
u32 initial_service_id = 0;
Bool auto_exit = GF_FALSE;
Bool logs_set = GF_FALSE;
Bool start_fs = GF_FALSE;
Bool use_rtix = GF_FALSE;
Bool pause_at_first = GF_FALSE;
Bool no_cfg_save = GF_FALSE;
Bool is_cfg_only = GF_FALSE;
Double play_from = 0;
#ifdef GPAC_MEMORY_TRACKING
GF_MemTrackerType mem_track = GF_MemTrackerNone;
#endif
Double fps = GF_IMPORT_DEFAULT_FPS;
Bool fill_ar, visible, do_uncache, has_command;
char *url_arg, *out_arg, *the_cfg, *rti_file, *views, *mosaic;
FILE *logfile = NULL;
Float scale = 1;
#ifndef WIN32
dlopen(NULL, RTLD_NOW|RTLD_GLOBAL);
#endif
/*by default use current dir*/
strcpy(the_url, ".");
memset(&user, 0, sizeof(GF_User));
dump_mode = DUMP_NONE;
fill_ar = visible = do_uncache = has_command = GF_FALSE;
url_arg = out_arg = the_cfg = rti_file = views = mosaic = NULL;
nb_times = 0;
times[0] = 0;
/*first locate config file if specified*/
for (i=1; i<(u32) argc; i++) {
char *arg = argv[i];
if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) {
the_cfg = argv[i+1];
i++;
}
else if (!strcmp(arg, "-mem-track") || !strcmp(arg, "-mem-track-stack")) {
#ifdef GPAC_MEMORY_TRACKING
mem_track = !strcmp(arg, "-mem-track-stack") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple;
#else
fprintf(stderr, "WARNING - GPAC not compiled with Memory Tracker - ignoring \"%s\"\n", arg);
#endif
} else if (!strcmp(arg, "-gui")) {
gui_mode = 1;
} else if (!strcmp(arg, "-guid")) {
gui_mode = 2;
} else if (!strcmp(arg, "-h") || !strcmp(arg, "-help")) {
PrintUsage();
return 0;
}
}
#ifdef GPAC_MEMORY_TRACKING
gf_sys_init(mem_track);
#else
gf_sys_init(GF_MemTrackerNone);
#endif
gf_sys_set_args(argc, (const char **) argv);
cfg_file = gf_cfg_init(the_cfg, NULL);
if (!cfg_file) {
fprintf(stderr, "Error: Configuration File not found\n");
return 1;
}
/*if logs are specified, use them*/
if (gf_log_set_tools_levels( gf_cfg_get_key(cfg_file, "General", "Logs") ) != GF_OK) {
return 1;
}
if( gf_cfg_get_key(cfg_file, "General", "Logs") != NULL ) {
logs_set = GF_TRUE;
}
if (!gui_mode) {
str = gf_cfg_get_key(cfg_file, "General", "ForceGUI");
if (str && !strcmp(str, "yes")) gui_mode = 1;
}
for (i=1; i<(u32) argc; i++) {
char *arg = argv[i];
if (!strcmp(arg, "-rti")) {
rti_file = argv[i+1];
i++;
} else if (!strcmp(arg, "-rtix")) {
rti_file = argv[i+1];
i++;
use_rtix = GF_TRUE;
} else if (!stricmp(arg, "-size")) {
/*usage of %ud breaks sscanf on MSVC*/
if (sscanf(argv[i+1], "%dx%d", &forced_width, &forced_height) != 2) {
forced_width = forced_height = 0;
}
i++;
} else if (!strcmp(arg, "-quiet")) {
be_quiet = 1;
} else if (!strcmp(arg, "-strict-error")) {
gf_log_set_strict_error(1);
} else if (!strcmp(arg, "-log-file") || !strcmp(arg, "-lf")) {
logfile = gf_fopen(argv[i+1], "wt");
gf_log_set_callback(logfile, on_gpac_log);
i++;
} else if (!strcmp(arg, "-logs") ) {
if (gf_log_set_tools_levels(argv[i+1]) != GF_OK) {
return 1;
}
logs_set = GF_TRUE;
i++;
} else if (!strcmp(arg, "-log-clock") || !strcmp(arg, "-lc")) {
log_time_start = 1;
} else if (!strcmp(arg, "-log-utc") || !strcmp(arg, "-lu")) {
log_utc_time = 1;
}
#if defined(__DARWIN__) || defined(__APPLE__)
else if (!strcmp(arg, "-thread")) threading_flags = 0;
#else
else if (!strcmp(arg, "-no-thread")) threading_flags = GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_WINDOW_NO_THREAD;
#endif
else if (!strcmp(arg, "-no-cthread") || !strcmp(arg, "-no-compositor-thread")) threading_flags |= GF_TERM_NO_COMPOSITOR_THREAD;
else if (!strcmp(arg, "-no-audio")) no_audio = 1;
else if (!strcmp(arg, "-no-regulation")) no_regulation = 1;
else if (!strcmp(arg, "-fs")) start_fs = 1;
else if (!strcmp(arg, "-opt")) {
set_cfg_option(argv[i+1]);
i++;
} else if (!strcmp(arg, "-conf")) {
set_cfg_option(argv[i+1]);
is_cfg_only=GF_TRUE;
i++;
}
else if (!strcmp(arg, "-ifce")) {
gf_cfg_set_key(cfg_file, "Network", "DefaultMCastInterface", argv[i+1]);
i++;
}
else if (!stricmp(arg, "-help")) {
PrintUsage();
return 1;
}
else if (!stricmp(arg, "-noprog")) {
no_prog=1;
gf_set_progress_callback(NULL, progress_quiet);
}
else if (!stricmp(arg, "-no-save") || !stricmp(arg, "--no-save") /*old versions used --n-save ...*/) {
no_cfg_save=1;
}
else if (!stricmp(arg, "-ntp-shift")) {
s32 shift = atoi(argv[i+1]);
i++;
gf_net_set_ntp_shift(shift);
}
else if (!stricmp(arg, "-run-for")) {
simulation_time_in_ms = atoi(argv[i+1]) * 1000;
if (!simulation_time_in_ms)
simulation_time_in_ms = 1; /*1ms*/
i++;
}
else if (!strcmp(arg, "-out")) {
out_arg = argv[i+1];
i++;
}
else if (!stricmp(arg, "-fps")) {
fps = atof(argv[i+1]);
i++;
} else if (!strcmp(arg, "-avi") || !strcmp(arg, "-sha")) {
dump_mode &= 0xFFFF0000;
if (!strcmp(arg, "-sha")) dump_mode |= DUMP_SHA1;
else dump_mode |= DUMP_AVI;
if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) {
if (!strcmp(arg, "-avi") && (nb_times!=2) ) {
fprintf(stderr, "Only one time arg found for -avi - check usage\n");
return 1;
}
i++;
}
} else if (!strcmp(arg, "-rgbds")) { /*get dump in rgbds pixel format*/
dump_mode |= DUMP_RGB_DEPTH_SHAPE;
} else if (!strcmp(arg, "-rgbd")) { /*get dump in rgbd pixel format*/
dump_mode |= DUMP_RGB_DEPTH;
} else if (!strcmp(arg, "-depth")) {
dump_mode |= DUMP_DEPTH_ONLY;
} else if (!strcmp(arg, "-bmp")) {
dump_mode &= 0xFFFF0000;
dump_mode |= DUMP_BMP;
if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++;
} else if (!strcmp(arg, "-png")) {
dump_mode &= 0xFFFF0000;
dump_mode |= DUMP_PNG;
if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++;
} else if (!strcmp(arg, "-raw")) {
dump_mode &= 0xFFFF0000;
dump_mode |= DUMP_RAW;
if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++;
} else if (!stricmp(arg, "-scale")) {
sscanf(argv[i+1], "%f", &scale);
i++;
}
else if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) {
/* already parsed */
i++;
}
/*arguments only used in non-gui mode*/
if (!gui_mode) {
if (arg[0] != '-') {
if (url_arg) {
fprintf(stderr, "Several input URLs provided (\"%s\", \"%s\"). Check your command-line.\n", url_arg, arg);
return 1;
}
url_arg = arg;
}
else if (!strcmp(arg, "-loop")) loop_at_end = 1;
else if (!strcmp(arg, "-bench")) bench_mode = 1;
else if (!strcmp(arg, "-vbench")) bench_mode = 2;
else if (!strcmp(arg, "-sbench")) bench_mode = 3;
else if (!strcmp(arg, "-no-addon")) enable_add_ons = GF_FALSE;
else if (!strcmp(arg, "-pause")) pause_at_first = 1;
else if (!strcmp(arg, "-play-from")) {
play_from = atof((const char *) argv[i+1]);
i++;
}
else if (!strcmp(arg, "-speed")) {
playback_speed = FLT2FIX( atof((const char *) argv[i+1]) );
if (playback_speed <= 0) playback_speed = FIX_ONE;
i++;
}
else if (!strcmp(arg, "-no-wnd")) user.init_flags |= GF_TERM_WINDOWLESS;
else if (!strcmp(arg, "-no-back")) user.init_flags |= GF_TERM_WINDOW_TRANSPARENT;
else if (!strcmp(arg, "-align")) {
if (argv[i+1][0]=='m') align_mode = 1;
else if (argv[i+1][0]=='b') align_mode = 2;
align_mode <<= 8;
if (argv[i+1][1]=='m') align_mode |= 1;
else if (argv[i+1][1]=='r') align_mode |= 2;
i++;
} else if (!strcmp(arg, "-fill")) {
fill_ar = GF_TRUE;
} else if (!strcmp(arg, "-show")) {
visible = 1;
} else if (!strcmp(arg, "-uncache")) {
do_uncache = GF_TRUE;
}
else if (!strcmp(arg, "-exit")) auto_exit = GF_TRUE;
else if (!stricmp(arg, "-views")) {
views = argv[i+1];
i++;
}
else if (!stricmp(arg, "-mosaic")) {
mosaic = argv[i+1];
i++;
}
else if (!stricmp(arg, "-com")) {
has_command = GF_TRUE;
i++;
}
else if (!stricmp(arg, "-service")) {
initial_service_id = atoi(argv[i+1]);
i++;
}
}
}
if (is_cfg_only) {
gf_cfg_del(cfg_file);
fprintf(stderr, "GPAC Config updated\n");
return 0;
}
if (do_uncache) {
const char *cache_dir = gf_cfg_get_key(cfg_file, "General", "CacheDirectory");
do_flatten_cache(cache_dir);
fprintf(stderr, "GPAC Cache dir %s flattened\n", cache_dir);
gf_cfg_del(cfg_file);
return 0;
}
if (dump_mode && !url_arg ) {
FILE *test;
url_arg = (char *)gf_cfg_get_key(cfg_file, "General", "StartupFile");
test = url_arg ? gf_fopen(url_arg, "rt") : NULL;
if (!test) url_arg = NULL;
else gf_fclose(test);
if (!url_arg) {
fprintf(stderr, "Missing argument for dump\n");
PrintUsage();
if (logfile) gf_fclose(logfile);
return 1;
}
}
if (!gui_mode && !url_arg && (gf_cfg_get_key(cfg_file, "General", "StartupFile") != NULL)) {
gui_mode=1;
}
#ifdef WIN32
if (gui_mode==1) {
const char *opt;
TCHAR buffer[1024];
DWORD res = GetCurrentDirectory(1024, buffer);
buffer[res] = 0;
opt = gf_cfg_get_key(cfg_file, "General", "ModulesDirectory");
if (strstr(opt, buffer)) {
gui_mode=1;
} else {
gui_mode=2;
}
}
#endif
if (gui_mode==1) {
hide_shell(1);
}
if (gui_mode) {
no_prog=1;
gf_set_progress_callback(NULL, progress_quiet);
}
if (!url_arg && simulation_time_in_ms)
simulation_time_in_ms += gf_sys_clock();
#if defined(__DARWIN__) || defined(__APPLE__)
carbon_init();
#endif
if (dump_mode) rti_file = NULL;
if (!logs_set) {
gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_WARNING);
}
if (rti_file || logfile || log_utc_time || log_time_start)
gf_log_set_callback(NULL, on_gpac_log);
if (rti_file) init_rti_logs(rti_file, url_arg, use_rtix);
{
GF_SystemRTInfo rti;
if (gf_sys_get_rti(0, &rti, 0))
fprintf(stderr, "System info: %d MB RAM - %d cores\n", (u32) (rti.physical_memory/1024/1024), rti.nb_cores);
}
/*setup dumping options*/
if (dump_mode) {
user.init_flags |= GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_REGULATION;
if (!visible)
user.init_flags |= GF_TERM_INIT_HIDE;
gf_cfg_set_key(cfg_file, "Audio", "DriverName", "Raw Audio Output");
no_cfg_save=GF_TRUE;
} else {
init_w = forced_width;
init_h = forced_height;
}
user.modules = gf_modules_new(NULL, cfg_file);
if (user.modules) i = gf_modules_get_count(user.modules);
if (!i || !user.modules) {
fprintf(stderr, "Error: no modules found - exiting\n");
if (user.modules) gf_modules_del(user.modules);
gf_cfg_del(cfg_file);
gf_sys_close();
if (logfile) gf_fclose(logfile);
return 1;
}
fprintf(stderr, "Modules Found : %d \n", i);
str = gf_cfg_get_key(cfg_file, "General", "GPACVersion");
if (!str || strcmp(str, GPAC_FULL_VERSION)) {
gf_cfg_del_section(cfg_file, "PluginsCache");
gf_cfg_set_key(cfg_file, "General", "GPACVersion", GPAC_FULL_VERSION);
}
user.config = cfg_file;
user.EventProc = GPAC_EventProc;
/*dummy in this case (global vars) but MUST be non-NULL*/
user.opaque = user.modules;
if (threading_flags) user.init_flags |= threading_flags;
if (no_audio) user.init_flags |= GF_TERM_NO_AUDIO;
if (no_regulation) user.init_flags |= GF_TERM_NO_REGULATION;
if (threading_flags & (GF_TERM_NO_DECODER_THREAD|GF_TERM_NO_COMPOSITOR_THREAD) ) term_step = GF_TRUE;
if (dump_mode) user.init_flags |= GF_TERM_USE_AUDIO_HW_CLOCK;
if (bench_mode) {
gf_cfg_discard_changes(user.config);
auto_exit = GF_TRUE;
gf_cfg_set_key(user.config, "Audio", "DriverName", "Raw Audio Output");
if (bench_mode!=2) {
gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output");
gf_cfg_set_key(user.config, "RAWVideo", "RawOutput", "null");
gf_cfg_set_key(user.config, "Compositor", "OpenGLMode", "disable");
} else {
gf_cfg_set_key(user.config, "Video", "DisableVSync", "yes");
}
}
{
char dim[50];
sprintf(dim, "%d", forced_width);
gf_cfg_set_key(user.config, "Compositor", "DefaultWidth", forced_width ? dim : NULL);
sprintf(dim, "%d", forced_height);
gf_cfg_set_key(user.config, "Compositor", "DefaultHeight", forced_height ? dim : NULL);
}
fprintf(stderr, "Loading GPAC Terminal\n");
i = gf_sys_clock();
term = gf_term_new(&user);
if (!term) {
fprintf(stderr, "\nInit error - check you have at least one video out and one rasterizer...\nFound modules:\n");
list_modules(user.modules);
gf_modules_del(user.modules);
gf_cfg_discard_changes(cfg_file);
gf_cfg_del(cfg_file);
gf_sys_close();
if (logfile) gf_fclose(logfile);
return 1;
}
fprintf(stderr, "Terminal Loaded in %d ms\n", gf_sys_clock()-i);
if (bench_mode) {
display_rti = 2;
gf_term_set_option(term, GF_OPT_VIDEO_BENCH, (bench_mode==3) ? 2 : 1);
if (bench_mode==1) bench_mode=2;
}
if (dump_mode) {
if (fill_ar) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN);
} else {
/*check video output*/
str = gf_cfg_get_key(cfg_file, "Video", "DriverName");
if (!bench_mode && !strcmp(str, "Raw Video Output")) fprintf(stderr, "WARNING: using raw output video (memory only) - no display used\n");
/*check audio output*/
str = gf_cfg_get_key(cfg_file, "Audio", "DriverName");
if (!str || !strcmp(str, "No Audio Output Available")) fprintf(stderr, "WARNING: no audio output available - make sure no other program is locking the sound card\n");
str = gf_cfg_get_key(cfg_file, "General", "NoMIMETypeFetch");
no_mime_check = (str && !stricmp(str, "yes")) ? 1 : 0;
}
str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Enabled");
if (str && !strcmp(str, "yes")) {
str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Name");
if (str) fprintf(stderr, "HTTP Proxy %s enabled\n", str);
}
if (rti_file) {
str = gf_cfg_get_key(cfg_file, "General", "RTIRefreshPeriod");
if (str) {
rti_update_time_ms = atoi(str);
} else {
gf_cfg_set_key(cfg_file, "General", "RTIRefreshPeriod", "200");
}
UpdateRTInfo("At GPAC load time\n");
}
Run = 1;
if (dump_mode) {
if (!nb_times) {
times[0] = 0;
nb_times++;
}
ret_val = dump_file(url_arg, out_arg, dump_mode, fps, forced_width, forced_height, scale, times, nb_times);
Run = 0;
}
else if (views) {
}
/*connect if requested*/
else if (!gui_mode && url_arg) {
char *ext;
if (strlen(url_arg) >= sizeof(the_url)) {
fprintf(stderr, "Input url %s is too long, truncating to %d chars.\n", url_arg, (int)(sizeof(the_url) - 1));
strncpy(the_url, url_arg, sizeof(the_url)-1);
the_url[sizeof(the_url) - 1] = 0;
}
else {
strcpy(the_url, url_arg);
}
ext = strrchr(the_url, '.');
if (ext && (!stricmp(ext, ".m3u") || !stricmp(ext, ".pls"))) {
GF_Err e = GF_OK;
fprintf(stderr, "Opening Playlist %s\n", the_url);
strcpy(pl_path, the_url);
/*this is not clean, we need to have a plugin handle playlist for ourselves*/
if (!strncmp("http:", the_url, 5)) {
GF_DownloadSession *sess = gf_dm_sess_new(term->downloader, the_url, GF_NETIO_SESSION_NOT_THREADED, NULL, NULL, &e);
if (sess) {
e = gf_dm_sess_process(sess);
if (!e) {
strncpy(the_url, gf_dm_sess_get_cache_name(sess), sizeof(the_url) - 1);
the_url[sizeof(the_cfg) - 1] = 0;
}
gf_dm_sess_del(sess);
}
}
playlist = e ? NULL : gf_fopen(the_url, "rt");
readonly_playlist = 1;
if (playlist) {
request_next_playlist_item = GF_TRUE;
} else {
if (e)
fprintf(stderr, "Failed to open playlist %s: %s\n", the_url, gf_error_to_string(e) );
fprintf(stderr, "Hit 'h' for help\n\n");
}
} else {
fprintf(stderr, "Opening URL %s\n", the_url);
if (pause_at_first) fprintf(stderr, "[Status: Paused]\n");
gf_term_connect_from_time(term, the_url, (u64) (play_from*1000), pause_at_first);
}
} else {
fprintf(stderr, "Hit 'h' for help\n\n");
str = gf_cfg_get_key(cfg_file, "General", "StartupFile");
if (str) {
strncpy(the_url, "MP4Client "GPAC_FULL_VERSION , sizeof(the_url)-1);
the_url[sizeof(the_url) - 1] = 0;
gf_term_connect(term, str);
startup_file = 1;
is_connected = 1;
}
}
if (gui_mode==2) gui_mode=0;
if (start_fs) gf_term_set_option(term, GF_OPT_FULLSCREEN, 1);
if (views) {
char szTemp[4046];
sprintf(szTemp, "views://%s", views);
gf_term_connect(term, szTemp);
}
if (mosaic) {
char szTemp[4046];
sprintf(szTemp, "mosaic://%s", mosaic);
gf_term_connect(term, szTemp);
}
if (bench_mode) {
rti_update_time_ms = 500;
bench_mode_start = gf_sys_clock();
}
while (Run) {
/*we don't want getchar to block*/
if ((gui_mode==1) || !gf_prompt_has_input()) {
if (reload) {
reload = 0;
gf_term_disconnect(term);
gf_term_connect(term, startup_file ? gf_cfg_get_key(cfg_file, "General", "StartupFile") : the_url);
}
if (restart && gf_term_get_option(term, GF_OPT_IS_OVER)) {
restart = 0;
gf_term_play_from_time(term, 0, 0);
}
if (request_next_playlist_item) {
c = '\n';
request_next_playlist_item = 0;
goto force_input;
}
if (has_command && is_connected) {
has_command = GF_FALSE;
for (i=0; i<(u32)argc; i++) {
if (!strcmp(argv[i], "-com")) {
gf_term_scene_update(term, NULL, argv[i+1]);
i++;
}
}
}
if (initial_service_id && is_connected) {
GF_ObjectManager *root_od = gf_term_get_root_object(term);
if (root_od) {
gf_term_select_service(term, root_od, initial_service_id);
initial_service_id = 0;
}
}
if (!use_rtix || display_rti) UpdateRTInfo(NULL);
if (term_step) {
gf_term_process_step(term);
} else {
gf_sleep(rti_update_time_ms);
}
if (auto_exit && eos_seen && gf_term_get_option(term, GF_OPT_IS_OVER)) {
Run = GF_FALSE;
}
/*sim time*/
if (simulation_time_in_ms
&& ( (gf_term_get_elapsed_time_in_ms(term)>simulation_time_in_ms) || (!url_arg && gf_sys_clock()>simulation_time_in_ms))
) {
Run = GF_FALSE;
}
continue;
}
c = gf_prompt_get_char();
force_input:
switch (c) {
case 'q':
{
GF_Event evt;
memset(&evt, 0, sizeof(GF_Event));
evt.type = GF_EVENT_QUIT;
gf_term_send_event(term, &evt);
}
break;
case 'X':
exit(0);
break;
case 'Q':
break;
case 'o':
startup_file = 0;
gf_term_disconnect(term);
fprintf(stderr, "Enter the absolute URL\n");
if (1 > scanf("%s", the_url)) {
fprintf(stderr, "Cannot read absolute URL, aborting\n");
break;
}
if (rti_file) init_rti_logs(rti_file, the_url, use_rtix);
gf_term_connect(term, the_url);
break;
case 'O':
gf_term_disconnect(term);
fprintf(stderr, "Enter the absolute URL to the playlist\n");
if (1 > scanf("%s", the_url)) {
fprintf(stderr, "Cannot read the absolute URL, aborting.\n");
break;
}
playlist = gf_fopen(the_url, "rt");
if (playlist) {
if (1 > fscanf(playlist, "%s", the_url)) {
fprintf(stderr, "Cannot read any URL from playlist, aborting.\n");
gf_fclose( playlist);
break;
}
fprintf(stderr, "Opening URL %s\n", the_url);
gf_term_connect(term, the_url);
}
break;
case '\n':
case 'N':
if (playlist) {
int res;
gf_term_disconnect(term);
res = fscanf(playlist, "%s", the_url);
if ((res == EOF) && loop_at_end) {
fseek(playlist, 0, SEEK_SET);
res = fscanf(playlist, "%s", the_url);
}
if (res == EOF) {
fprintf(stderr, "No more items - exiting\n");
Run = 0;
} else if (the_url[0] == '#') {
request_next_playlist_item = GF_TRUE;
} else {
fprintf(stderr, "Opening URL %s\n", the_url);
gf_term_connect_with_path(term, the_url, pl_path);
}
}
break;
case 'P':
if (playlist) {
u32 count;
gf_term_disconnect(term);
if (1 > scanf("%u", &count)) {
fprintf(stderr, "Cannot read number, aborting.\n");
break;
}
while (count) {
if (fscanf(playlist, "%s", the_url)) {
fprintf(stderr, "Failed to read line, aborting\n");
break;
}
count--;
}
fprintf(stderr, "Opening URL %s\n", the_url);
gf_term_connect(term, the_url);
}
break;
case 'r':
if (is_connected)
reload = 1;
break;
case 'D':
if (is_connected) gf_term_disconnect(term);
break;
case 'p':
if (is_connected) {
Bool is_pause = gf_term_get_option(term, GF_OPT_PLAY_STATE);
fprintf(stderr, "[Status: %s]\n", is_pause ? "Playing" : "Paused");
gf_term_set_option(term, GF_OPT_PLAY_STATE, is_pause ? GF_STATE_PLAYING : GF_STATE_PAUSED);
}
break;
case 's':
if (is_connected) {
gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE);
fprintf(stderr, "Step time: ");
PrintTime(gf_term_get_time_in_ms(term));
fprintf(stderr, "\n");
}
break;
case 'z':
case 'T':
if (!CanSeek || (Duration<=2000)) {
fprintf(stderr, "scene not seekable\n");
} else {
Double res;
s32 seekTo;
fprintf(stderr, "Duration: ");
PrintTime(Duration);
res = gf_term_get_time_in_ms(term);
if (c=='z') {
res *= 100;
res /= (s64)Duration;
fprintf(stderr, " (current %.2f %%)\nEnter Seek percentage:\n", res);
if (scanf("%d", &seekTo) == 1) {
if (seekTo > 100) seekTo = 100;
res = (Double)(s64)Duration;
res /= 100;
res *= seekTo;
gf_term_play_from_time(term, (u64) (s64) res, 0);
}
} else {
u32 r, h, m, s;
fprintf(stderr, " - Current Time: ");
PrintTime((u64) res);
fprintf(stderr, "\nEnter seek time (Format: s, m:s or h:m:s):\n");
h = m = s = 0;
r =scanf("%d:%d:%d", &h, &m, &s);
if (r==2) {
s = m;
m = h;
h = 0;
}
else if (r==1) {
s = h;
m = h = 0;
}
if (r && (r<=3)) {
u64 time = h*3600 + m*60 + s;
gf_term_play_from_time(term, time*1000, 0);
}
}
}
break;
case 't':
{
if (is_connected) {
fprintf(stderr, "Current Time: ");
PrintTime(gf_term_get_time_in_ms(term));
fprintf(stderr, " - Duration: ");
PrintTime(Duration);
fprintf(stderr, "\n");
}
}
break;
case 'w':
if (is_connected) PrintWorldInfo(term);
break;
case 'v':
if (is_connected) PrintODList(term, NULL, 0, 0, "Root");
break;
case 'i':
if (is_connected) {
u32 ID;
fprintf(stderr, "Enter OD ID (0 for main OD): ");
fflush(stderr);
if (scanf("%ud", &ID) == 1) {
ViewOD(term, ID, (u32)-1, NULL);
} else {
char str_url[GF_MAX_PATH];
if (scanf("%s", str_url) == 1)
ViewOD(term, 0, (u32)-1, str_url);
}
}
break;
case 'j':
if (is_connected) {
u32 num;
do {
fprintf(stderr, "Enter OD number (0 for main OD): ");
fflush(stderr);
} while( 1 > scanf("%ud", &num));
ViewOD(term, (u32)-1, num, NULL);
}
break;
case 'b':
if (is_connected) ViewODs(term, 1);
break;
case 'm':
if (is_connected) ViewODs(term, 0);
break;
case 'l':
list_modules(user.modules);
break;
case 'n':
if (is_connected) set_navigation();
break;
case 'x':
if (is_connected) gf_term_set_option(term, GF_OPT_NAVIGATION_TYPE, 0);
break;
case 'd':
if (is_connected) {
GF_ObjectManager *odm = NULL;
char radname[GF_MAX_PATH], *sExt;
GF_Err e;
u32 i, count, odid;
Bool xml_dump, std_out;
radname[0] = 0;
do {
fprintf(stderr, "Enter Inline OD ID if any or 0 : ");
fflush(stderr);
} while( 1 > scanf("%ud", &odid));
if (odid) {
GF_ObjectManager *root_odm = gf_term_get_root_object(term);
if (!root_odm) break;
count = gf_term_get_object_count(term, root_odm);
for (i=0; i<count; i++) {
GF_MediaInfo info;
odm = gf_term_get_object(term, root_odm, i);
if (gf_term_get_object_info(term, odm, &info) == GF_OK) {
if (info.od->objectDescriptorID==odid) break;
}
odm = NULL;
}
}
do {
fprintf(stderr, "Enter file radical name (+\'.x\' for XML dumping) - \"std\" for stderr: ");
fflush(stderr);
} while( 1 > scanf("%s", radname));
sExt = strrchr(radname, '.');
xml_dump = 0;
if (sExt) {
if (!stricmp(sExt, ".x")) xml_dump = 1;
sExt[0] = 0;
}
std_out = strnicmp(radname, "std", 3) ? 0 : 1;
e = gf_term_dump_scene(term, std_out ? NULL : radname, NULL, xml_dump, 0, odm);
fprintf(stderr, "Dump done (%s)\n", gf_error_to_string(e));
}
break;
case 'c':
PrintGPACConfig();
break;
case '3':
{
Bool use_3d = !gf_term_get_option(term, GF_OPT_USE_OPENGL);
if (gf_term_set_option(term, GF_OPT_USE_OPENGL, use_3d)==GF_OK) {
fprintf(stderr, "Using %s for 2D drawing\n", use_3d ? "OpenGL" : "2D rasterizer");
}
}
break;
case 'k':
{
Bool opt = gf_term_get_option(term, GF_OPT_STRESS_MODE);
opt = !opt;
fprintf(stderr, "Turning stress mode %s\n", opt ? "on" : "off");
gf_term_set_option(term, GF_OPT_STRESS_MODE, opt);
}
break;
case '4':
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3);
break;
case '5':
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9);
break;
case '6':
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN);
break;
case '7':
gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP);
break;
case 'C':
switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) {
case GF_MEDIA_CACHE_DISABLED:
gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_ENABLED);
break;
case GF_MEDIA_CACHE_ENABLED:
gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_DISABLED);
break;
case GF_MEDIA_CACHE_RUNNING:
fprintf(stderr, "Streaming Cache is running - please stop it first\n");
continue;
}
switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) {
case GF_MEDIA_CACHE_ENABLED:
fprintf(stderr, "Streaming Cache Enabled\n");
break;
case GF_MEDIA_CACHE_DISABLED:
fprintf(stderr, "Streaming Cache Disabled\n");
break;
case GF_MEDIA_CACHE_RUNNING:
fprintf(stderr, "Streaming Cache Running\n");
break;
}
break;
case 'S':
case 'A':
if (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)==GF_MEDIA_CACHE_RUNNING) {
gf_term_set_option(term, GF_OPT_MEDIA_CACHE, (c=='S') ? GF_MEDIA_CACHE_DISABLED : GF_MEDIA_CACHE_DISCARD);
fprintf(stderr, "Streaming Cache stopped\n");
} else {
fprintf(stderr, "Streaming Cache not running\n");
}
break;
case 'R':
display_rti = !display_rti;
ResetCaption();
break;
case 'F':
if (display_rti) display_rti = 0;
else display_rti = 2;
ResetCaption();
break;
case 'u':
{
GF_Err e;
char szCom[8192];
fprintf(stderr, "Enter command to send:\n");
fflush(stdin);
szCom[0] = 0;
if (1 > scanf("%[^\t\n]", szCom)) {
fprintf(stderr, "Cannot read command to send, aborting.\n");
break;
}
e = gf_term_scene_update(term, NULL, szCom);
if (e) fprintf(stderr, "Processing command failed: %s\n", gf_error_to_string(e));
}
break;
case 'e':
{
GF_Err e;
char jsCode[8192];
fprintf(stderr, "Enter JavaScript code to evaluate:\n");
fflush(stdin);
jsCode[0] = 0;
if (1 > scanf("%[^\t\n]", jsCode)) {
fprintf(stderr, "Cannot read code to evaluate, aborting.\n");
break;
}
e = gf_term_scene_update(term, "application/ecmascript", jsCode);
if (e) fprintf(stderr, "Processing JS code failed: %s\n", gf_error_to_string(e));
}
break;
case 'L':
{
char szLog[1024], *cur_logs;
cur_logs = gf_log_get_tools_levels();
fprintf(stderr, "Enter new log level (current tools %s):\n", cur_logs);
gf_free(cur_logs);
if (scanf("%s", szLog) < 1) {
fprintf(stderr, "Cannot read new log level, aborting.\n");
break;
}
gf_log_modify_tools_levels(szLog);
}
break;
case 'g':
{
GF_SystemRTInfo rti;
gf_sys_get_rti(rti_update_time_ms, &rti, 0);
fprintf(stderr, "GPAC allocated memory "LLD"\n", rti.gpac_memory);
}
break;
case 'M':
{
u32 size;
do {
fprintf(stderr, "Enter new video cache memory in kBytes (current %ud):\n", gf_term_get_option(term, GF_OPT_VIDEO_CACHE_SIZE));
} while (1 > scanf("%ud", &size));
gf_term_set_option(term, GF_OPT_VIDEO_CACHE_SIZE, size);
}
break;
case 'H':
{
u32 http_bitrate = gf_term_get_option(term, GF_OPT_HTTP_MAX_RATE);
do {
fprintf(stderr, "Enter new http bitrate in bps (0 for none) - current limit: %d\n", http_bitrate);
} while (1 > scanf("%ud", &http_bitrate));
gf_term_set_option(term, GF_OPT_HTTP_MAX_RATE, http_bitrate);
}
break;
case 'E':
gf_term_set_option(term, GF_OPT_RELOAD_CONFIG, 1);
break;
case 'B':
switch_bench(!bench_mode);
break;
case 'Y':
{
char szOpt[8192];
fprintf(stderr, "Enter option to set (Section:Name=Value):\n");
fflush(stdin);
szOpt[0] = 0;
if (1 > scanf("%[^\t\n]", szOpt)) {
fprintf(stderr, "Cannot read option\n");
break;
}
set_cfg_option(szOpt);
}
break;
/*extract to PNG*/
case 'Z':
{
char szFileName[100];
u32 nb_pass, nb_views, offscreen_view = 0;
GF_VideoSurface fb;
GF_Err e;
nb_pass = 1;
nb_views = gf_term_get_option(term, GF_OPT_NUM_STEREO_VIEWS);
if (nb_views>1) {
fprintf(stderr, "Auto-stereo mode detected - type number of view to dump (0 is main output, 1 to %d offscreen view, %d for all offscreen, %d for all offscreen and main)\n", nb_views, nb_views+1, nb_views+2);
if (scanf("%d", &offscreen_view) != 1) {
offscreen_view = 0;
}
if (offscreen_view==nb_views+1) {
offscreen_view = 1;
nb_pass = nb_views;
}
else if (offscreen_view==nb_views+2) {
offscreen_view = 0;
nb_pass = nb_views+1;
}
}
while (nb_pass) {
nb_pass--;
if (offscreen_view) {
sprintf(szFileName, "view%d_dump.png", offscreen_view);
e = gf_term_get_offscreen_buffer(term, &fb, offscreen_view-1, 0);
} else {
sprintf(szFileName, "gpac_video_dump_"LLU".png", gf_net_get_utc() );
e = gf_term_get_screen_buffer(term, &fb);
}
offscreen_view++;
if (e) {
fprintf(stderr, "Error dumping screen buffer %s\n", gf_error_to_string(e) );
nb_pass = 0;
} else {
#ifndef GPAC_DISABLE_AV_PARSERS
u32 dst_size = fb.width*fb.height*4;
char *dst = (char*)gf_malloc(sizeof(char)*dst_size);
e = gf_img_png_enc(fb.video_buffer, fb.width, fb.height, fb.pitch_y, fb.pixel_format, dst, &dst_size);
if (e) {
fprintf(stderr, "Error encoding PNG %s\n", gf_error_to_string(e) );
nb_pass = 0;
} else {
FILE *png = gf_fopen(szFileName, "wb");
if (!png) {
fprintf(stderr, "Error writing file %s\n", szFileName);
nb_pass = 0;
} else {
gf_fwrite(dst, dst_size, 1, png);
gf_fclose(png);
fprintf(stderr, "Dump to %s\n", szFileName);
}
}
if (dst) gf_free(dst);
gf_term_release_screen_buffer(term, &fb);
#endif //GPAC_DISABLE_AV_PARSERS
}
}
fprintf(stderr, "Done: %s\n", szFileName);
}
break;
case 'G':
{
GF_ObjectManager *root_od, *odm;
u32 index;
char szOpt[8192];
fprintf(stderr, "Enter 0-based index of object to select or service ID:\n");
fflush(stdin);
szOpt[0] = 0;
if (1 > scanf("%[^\t\n]", szOpt)) {
fprintf(stderr, "Cannot read OD ID\n");
break;
}
index = atoi(szOpt);
odm = NULL;
root_od = gf_term_get_root_object(term);
if (root_od) {
if ( gf_term_find_service(term, root_od, index)) {
gf_term_select_service(term, root_od, index);
} else {
fprintf(stderr, "Cannot find service %d - trying with object index\n", index);
odm = gf_term_get_object(term, root_od, index);
if (odm) {
gf_term_select_object(term, odm);
} else {
fprintf(stderr, "Cannot find object at index %d\n", index);
}
}
}
}
break;
case 'h':
PrintHelp();
break;
default:
break;
}
}
if (bench_mode) {
PrintAVInfo(GF_TRUE);
}
/*FIXME: we have an issue in cleaning up after playing in bench mode and run-for 0 (buildbot tests). We for now disable error checks after run-for is done*/
if (simulation_time_in_ms) {
gf_log_set_strict_error(0);
}
i = gf_sys_clock();
gf_term_disconnect(term);
if (rti_file) UpdateRTInfo("Disconnected\n");
fprintf(stderr, "Deleting terminal... ");
if (playlist) gf_fclose(playlist);
#if defined(__DARWIN__) || defined(__APPLE__)
carbon_uninit();
#endif
gf_term_del(term);
fprintf(stderr, "done (in %d ms) - ran for %d ms\n", gf_sys_clock() - i, gf_sys_clock());
fprintf(stderr, "GPAC cleanup ...\n");
gf_modules_del(user.modules);
if (no_cfg_save)
gf_cfg_discard_changes(cfg_file);
gf_cfg_del(cfg_file);
gf_sys_close();
if (rti_logs) gf_fclose(rti_logs);
if (logfile) gf_fclose(logfile);
if (gui_mode) {
hide_shell(2);
}
#ifdef GPAC_MEMORY_TRACKING
if (mem_track && (gf_memory_size() || gf_file_handles_count() )) {
gf_log_set_tool_level(GF_LOG_MEMORY, GF_LOG_INFO);
gf_memory_print();
return 2;
}
#endif
return ret_val;
}
|
CWE-787
| 182,959 | 4,142 |
33731538446325953772163374479888140209
| null | null | null |
gpac
|
35ab4475a7df9b2a4bcab235e379c0c3ec543658
| 1 |
GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command)
{
CATEnum cat_enum;
char *sep;
cat_enum.dest = dest;
cat_enum.import_flags = import_flags;
cat_enum.force_fps = force_fps;
cat_enum.frames_per_sample = frames_per_sample;
cat_enum.tmp_dir = tmp_dir;
cat_enum.force_cat = force_cat;
cat_enum.align_timelines = align_timelines;
cat_enum.allow_add_in_command = allow_add_in_command;
strcpy(cat_enum.szPath, fileName);
sep = strrchr(cat_enum.szPath, GF_PATH_SEPARATOR);
if (!sep) sep = strrchr(cat_enum.szPath, '/');
if (!sep) {
strcpy(cat_enum.szPath, ".");
strcpy(cat_enum.szRad1, fileName);
} else {
strcpy(cat_enum.szRad1, sep+1);
sep[0] = 0;
}
sep = strchr(cat_enum.szRad1, '*');
strcpy(cat_enum.szRad2, sep+1);
sep[0] = 0;
sep = strchr(cat_enum.szRad2, '%');
if (!sep) sep = strchr(cat_enum.szRad2, '#');
if (!sep) sep = strchr(cat_enum.szRad2, ':');
strcpy(cat_enum.szOpt, "");
if (sep) {
strcpy(cat_enum.szOpt, sep);
sep[0] = 0;
}
return gf_enum_directory(cat_enum.szPath, 0, cat_enumerate, &cat_enum, NULL);
}
|
CWE-119
| 182,960 | 4,143 |
184974595979519972400668791979192791271
| null | null | null |
gpac
|
35ab4475a7df9b2a4bcab235e379c0c3ec543658
| 1 |
GF_Err gf_sm_load_init(GF_SceneLoader *load)
{
GF_Err e = GF_NOT_SUPPORTED;
char *ext, szExt[50];
/*we need at least a scene graph*/
if (!load || (!load->ctx && !load->scene_graph)
#ifndef GPAC_DISABLE_ISOM
|| (!load->fileName && !load->isom && !(load->flags & GF_SM_LOAD_FOR_PLAYBACK) )
#endif
) return GF_BAD_PARAM;
if (!load->type) {
#ifndef GPAC_DISABLE_ISOM
if (load->isom) {
load->type = GF_SM_LOAD_MP4;
} else
#endif
{
ext = (char *)strrchr(load->fileName, '.');
if (!ext) return GF_NOT_SUPPORTED;
if (!stricmp(ext, ".gz")) {
char *anext;
ext[0] = 0;
anext = (char *)strrchr(load->fileName, '.');
ext[0] = '.';
ext = anext;
}
strcpy(szExt, &ext[1]);
strlwr(szExt);
if (strstr(szExt, "bt")) load->type = GF_SM_LOAD_BT;
else if (strstr(szExt, "wrl")) load->type = GF_SM_LOAD_VRML;
else if (strstr(szExt, "x3dv")) load->type = GF_SM_LOAD_X3DV;
#ifndef GPAC_DISABLE_LOADER_XMT
else if (strstr(szExt, "xmt") || strstr(szExt, "xmta")) load->type = GF_SM_LOAD_XMTA;
else if (strstr(szExt, "x3d")) load->type = GF_SM_LOAD_X3D;
#endif
else if (strstr(szExt, "swf")) load->type = GF_SM_LOAD_SWF;
else if (strstr(szExt, "mov")) load->type = GF_SM_LOAD_QT;
else if (strstr(szExt, "svg")) load->type = GF_SM_LOAD_SVG;
else if (strstr(szExt, "xsr")) load->type = GF_SM_LOAD_XSR;
else if (strstr(szExt, "xbl")) load->type = GF_SM_LOAD_XBL;
else if (strstr(szExt, "xml")) {
char *rtype = gf_xml_get_root_type(load->fileName, &e);
if (rtype) {
if (!strcmp(rtype, "SAFSession")) load->type = GF_SM_LOAD_XSR;
else if (!strcmp(rtype, "XMT-A")) load->type = GF_SM_LOAD_XMTA;
else if (!strcmp(rtype, "X3D")) load->type = GF_SM_LOAD_X3D;
else if (!strcmp(rtype, "bindings")) load->type = GF_SM_LOAD_XBL;
gf_free(rtype);
}
}
}
}
if (!load->type) return e;
if (!load->scene_graph) load->scene_graph = load->ctx->scene_graph;
switch (load->type) {
#ifndef GPAC_DISABLE_LOADER_BT
case GF_SM_LOAD_BT:
case GF_SM_LOAD_VRML:
case GF_SM_LOAD_X3DV:
return gf_sm_load_init_bt(load);
#endif
#ifndef GPAC_DISABLE_LOADER_XMT
case GF_SM_LOAD_XMTA:
case GF_SM_LOAD_X3D:
return gf_sm_load_init_xmt(load);
#endif
#ifndef GPAC_DISABLE_SVG
case GF_SM_LOAD_SVG:
case GF_SM_LOAD_XSR:
case GF_SM_LOAD_DIMS:
return gf_sm_load_init_svg(load);
case GF_SM_LOAD_XBL:
e = gf_sm_load_init_xbl(load);
load->process = gf_sm_load_run_xbl;
load->done = gf_sm_load_done_xbl;
return e;
#endif
#ifndef GPAC_DISABLE_SWF_IMPORT
case GF_SM_LOAD_SWF:
return gf_sm_load_init_swf(load);
#endif
#ifndef GPAC_DISABLE_LOADER_ISOM
case GF_SM_LOAD_MP4:
return gf_sm_load_init_isom(load);
#endif
#ifndef GPAC_DISABLE_QTVR
case GF_SM_LOAD_QT:
return gf_sm_load_init_qt(load);
#endif
default:
return GF_NOT_SUPPORTED;
}
return GF_NOT_SUPPORTED;
}
|
CWE-119
| 182,965 | 4,147 |
297086645771880512407195498276494895623
| null | null | null |
rdesktop
|
4dca546d04321a610c1835010b5dad85163b65e1
| 1 |
process_plane(uint8 * in, int width, int height, uint8 * out, int size)
{
UNUSED(size);
int indexw;
int indexh;
int code;
int collen;
int replen;
int color;
int x;
int revcode;
uint8 * last_line;
uint8 * this_line;
uint8 * org_in;
uint8 * org_out;
org_in = in;
org_out = out;
last_line = 0;
indexh = 0;
while (indexh < height)
{
out = (org_out + width * height * 4) - ((indexh + 1) * width * 4);
color = 0;
this_line = out;
indexw = 0;
if (last_line == 0)
{
while (indexw < width)
{
code = CVAL(in);
replen = code & 0xf;
collen = (code >> 4) & 0xf;
revcode = (replen << 4) | collen;
if ((revcode <= 47) && (revcode >= 16))
{
replen = revcode;
collen = 0;
}
while (collen > 0)
{
color = CVAL(in);
*out = color;
out += 4;
indexw++;
collen--;
}
while (replen > 0)
{
*out = color;
out += 4;
indexw++;
replen--;
}
}
}
else
{
while (indexw < width)
{
code = CVAL(in);
replen = code & 0xf;
collen = (code >> 4) & 0xf;
revcode = (replen << 4) | collen;
if ((revcode <= 47) && (revcode >= 16))
{
replen = revcode;
collen = 0;
}
while (collen > 0)
{
x = CVAL(in);
if (x & 1)
{
x = x >> 1;
x = x + 1;
color = -x;
}
else
{
x = x >> 1;
color = x;
}
x = last_line[indexw * 4] + color;
*out = x;
out += 4;
indexw++;
collen--;
}
while (replen > 0)
{
x = last_line[indexw * 4] + color;
*out = x;
out += 4;
indexw++;
replen--;
}
}
}
indexh++;
last_line = this_line;
}
return (int) (in - org_in);
}
|
CWE-119
| 182,967 | 4,149 |
243072446217365995170623123541267501728
| null | null | null |
rdesktop
|
4dca546d04321a610c1835010b5dad85163b65e1
| 1 |
cssp_read_tsrequest(STREAM token, STREAM pubkey)
{
STREAM s;
int length;
int tagval;
s = tcp_recv(NULL, 4);
if (s == NULL)
return False;
if (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
{
logger(Protocol, Error,
"cssp_read_tsrequest(), expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x",
s->p[0]);
return False;
}
if (s->p[1] < 0x80)
length = s->p[1] - 2;
else if (s->p[1] == 0x81)
length = s->p[2] - 1;
else if (s->p[1] == 0x82)
length = (s->p[2] << 8) | s->p[3];
else
return False;
s = tcp_recv(s, length);
if (!ber_in_header(s, &tagval, &length) ||
tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
return False;
if (!ber_in_header(s, &tagval, &length) ||
tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))
return False;
in_uint8s(s, length);
if (token)
{
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1))
return False;
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
return False;
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED))
return False;
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))
return False;
if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)
return False;
token->end = token->p = token->data;
out_uint8p(token, s->p, length);
s_mark_end(token);
}
if (pubkey)
{
if (!ber_in_header(s, &tagval, &length)
|| tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3))
return False;
if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)
return False;
pubkey->data = pubkey->p = s->p;
pubkey->end = pubkey->data + length;
pubkey->size = length;
}
return True;
}
|
CWE-119
| 182,969 | 4,151 |
154298624846793852867923020674033022485
| null | null | null |
rdesktop
|
4dca546d04321a610c1835010b5dad85163b65e1
| 1 |
process_bitmap_updates(STREAM s)
{
uint16 num_updates;
uint16 left, top, right, bottom, width, height;
uint16 cx, cy, bpp, Bpp, compress, bufsize, size;
uint8 *data, *bmpdata;
int i;
logger(Protocol, Debug, "%s()", __func__);
in_uint16_le(s, num_updates);
for (i = 0; i < num_updates; i++)
{
in_uint16_le(s, left);
in_uint16_le(s, top);
in_uint16_le(s, right);
in_uint16_le(s, bottom);
in_uint16_le(s, width);
in_uint16_le(s, height);
in_uint16_le(s, bpp);
Bpp = (bpp + 7) / 8;
in_uint16_le(s, compress);
in_uint16_le(s, bufsize);
cx = right - left + 1;
cy = bottom - top + 1;
logger(Graphics, Debug,
"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d",
left, top, right, bottom, width, height, Bpp, compress);
if (!compress)
{
int y;
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
for (y = 0; y < height; y++)
{
in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],
width * Bpp);
}
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
xfree(bmpdata);
continue;
}
if (compress & 0x400)
{
size = bufsize;
}
else
{
in_uint8s(s, 2); /* pad */
in_uint16_le(s, size);
in_uint8s(s, 4); /* line_size, final_size */
}
in_uint8p(s, data, size);
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
if (bitmap_decompress(bmpdata, width, height, data, size, Bpp))
{
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
}
else
{
logger(Graphics, Warning,
"process_bitmap_updates(), failed to decompress bitmap");
}
xfree(bmpdata);
}
}
|
CWE-119
| 182,974 | 4,154 |
255073384789805870442906046360338886220
| null | null | null |
rdesktop
|
4dca546d04321a610c1835010b5dad85163b65e1
| 1 |
process_demand_active(STREAM s)
{
uint8 type;
uint16 len_src_descriptor, len_combined_caps;
/* at this point we need to ensure that we have ui created */
rd_create_ui();
in_uint32_le(s, g_rdp_shareid);
in_uint16_le(s, len_src_descriptor);
in_uint16_le(s, len_combined_caps);
in_uint8s(s, len_src_descriptor);
logger(Protocol, Debug, "process_demand_active(), shareid=0x%x", g_rdp_shareid);
rdp_process_server_caps(s, len_combined_caps);
rdp_send_confirm_active();
rdp_send_synchronise();
rdp_send_control(RDP_CTL_COOPERATE);
rdp_send_control(RDP_CTL_REQUEST_CONTROL);
rdp_recv(&type); /* RDP_PDU_SYNCHRONIZE */
rdp_recv(&type); /* RDP_CTL_COOPERATE */
rdp_recv(&type); /* RDP_CTL_GRANT_CONTROL */
rdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0,
g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0);
if (g_rdp_version >= RDP_V5)
{
rdp_enum_bmpcache2();
rdp_send_fonts(3);
}
else
{
rdp_send_fonts(1);
rdp_send_fonts(2);
}
rdp_recv(&type); /* RDP_PDU_UNKNOWN 0x28 (Fonts?) */
reset_order_state();
}
|
CWE-119
| 182,975 | 4,155 |
50427493118138852521746247548508204331
| null | null | null |
rdesktop
|
4dca546d04321a610c1835010b5dad85163b65e1
| 1 |
rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size)
{
static iconv_t icv_utf16_to_local;
size_t ibl, obl;
char *pin, *pout;
if (!icv_utf16_to_local)
{
icv_utf16_to_local = iconv_open(g_codepage, WINDOWS_CODEPAGE);
if (icv_utf16_to_local == (iconv_t) - 1)
{
logger(Protocol, Error, "rdp_in_unistr(), iconv_open[%s -> %s] fail %p",
WINDOWS_CODEPAGE, g_codepage, icv_utf16_to_local);
abort();
}
}
/* Dynamic allocate of destination string if not provided */
if (*string == NULL)
{
*string = xmalloc(in_len * 2);
*str_size = in_len * 2;
}
ibl = in_len;
obl = *str_size - 1;
pin = (char *) s->p;
pout = *string;
if (iconv(icv_utf16_to_local, (char **) &pin, &ibl, &pout, &obl) == (size_t) - 1)
{
if (errno == E2BIG)
{
logger(Protocol, Warning,
"rdp_in_unistr(), server sent an unexpectedly long string, truncating");
}
else
{
logger(Protocol, Warning, "rdp_in_unistr(), iconv fail, errno %d", errno);
free(*string);
*string = NULL;
*str_size = 0;
}
abort();
}
/* we must update the location of the current STREAM for future reads of s->p */
s->p += in_len;
*pout = 0;
if (*string)
*str_size = pout - *string;
}
|
CWE-119
| 182,976 | 4,156 |
87473831233998539034855949088003907593
| null | null | null |
rdesktop
|
4dca546d04321a610c1835010b5dad85163b65e1
| 1 |
rdpdr_process(STREAM s)
{
uint32 handle;
uint16 vmin;
uint16 component;
uint16 pakid;
logger(Protocol, Debug, "rdpdr_process()");
/* hexdump(s->p, s->end - s->p); */
in_uint16(s, component);
in_uint16(s, pakid);
if (component == RDPDR_CTYP_CORE)
{
switch (pakid)
{
case PAKID_CORE_DEVICE_IOREQUEST:
rdpdr_process_irp(s);
break;
case PAKID_CORE_SERVER_ANNOUNCE:
/* DR_CORE_SERVER_ANNOUNCE_REQ */
in_uint8s(s, 2); /* skip versionMajor */
in_uint16_le(s, vmin); /* VersionMinor */
in_uint32_le(s, g_client_id); /* ClientID */
/* The RDP client is responsibility to provide a random client id
if server version is < 12 */
if (vmin < 0x000c)
g_client_id = 0x815ed39d; /* IP address (use 127.0.0.1) 0x815ed39d */
g_epoch++;
#if WITH_SCARD
/*
* We need to release all SCARD contexts to end all
* current transactions and pending calls
*/
scard_release_all_contexts();
/*
* According to [MS-RDPEFS] 3.2.5.1.2:
*
* If this packet appears after a sequence of other packets,
* it is a signal that the server has reconnected to a new session
* and the whole sequence has been reset. The client MUST treat
* this packet as the beginning of a new sequence.
* The client MUST also cancel all outstanding requests and release
* previous references to all devices.
*
* If any problem arises in the future, please, pay attention to the
* "If this packet appears after a sequence of other packets" part
*
*/
#endif
rdpdr_send_client_announce_reply();
rdpdr_send_client_name_request();
break;
case PAKID_CORE_CLIENTID_CONFIRM:
rdpdr_send_client_device_list_announce();
break;
case PAKID_CORE_DEVICE_REPLY:
in_uint32(s, handle);
logger(Protocol, Debug,
"rdpdr_process(), server connected to resource %d", handle);
break;
case PAKID_CORE_SERVER_CAPABILITY:
rdpdr_send_client_capability_response();
break;
default:
logger(Protocol, Debug,
"rdpdr_process(), pakid 0x%x of component 0x%x", pakid,
component);
break;
}
}
else if (component == RDPDR_CTYP_PRN)
{
if (pakid == PAKID_PRN_CACHE_DATA)
printercache_process(s);
}
else
logger(Protocol, Warning, "rdpdr_process(), unhandled component 0x%x", component);
}
|
CWE-119
| 182,977 | 4,157 |
130790675046993948452991300609520775416
| null | null | null |
rdesktop
|
4dca546d04321a610c1835010b5dad85163b65e1
| 1 |
seamless_process(STREAM s)
{
unsigned int pkglen;
char *buf;
pkglen = s->end - s->p;
/* str_handle_lines requires null terminated strings */
buf = xmalloc(pkglen + 1);
STRNCPY(buf, (char *) s->p, pkglen + 1);
str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL);
xfree(buf);
}
|
CWE-119
| 182,980 | 4,159 |
58925099420725391388605492678330289377
| null | null | null |
tcpdump
|
24182d959f661327525a20d9a94c98a8ec016778
| 1 |
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);
}
|
CWE-674
| 182,986 | 4,163 |
244595164974697581097700410348880100739
| null | null | null |
tcpdump
|
96480ab95308cd9234b4f09b175ebf60e17792c6
| 1 |
print_trans(netdissect_options *ndo,
const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf)
{
u_int bcc;
const char *f1, *f2, *f3, *f4;
const u_char *data, *param;
const u_char *w = words + 1;
int datalen, paramlen;
if (request) {
ND_TCHECK2(w[12 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 9 * 2);
param = buf + EXTRACT_LE_16BITS(w + 10 * 2);
datalen = EXTRACT_LE_16BITS(w + 11 * 2);
data = buf + EXTRACT_LE_16BITS(w + 12 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n";
f2 = "|Name=[S]\n";
f3 = "|Param ";
f4 = "|Data ";
} else {
ND_TCHECK2(w[7 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 3 * 2);
param = buf + EXTRACT_LE_16BITS(w + 4 * 2);
datalen = EXTRACT_LE_16BITS(w + 6 * 2);
data = buf + EXTRACT_LE_16BITS(w + 7 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n";
f2 = "|Unknown ";
f3 = "|Param ";
f4 = "|Data ";
}
smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf),
unicodestr);
ND_TCHECK2(*data1, 2);
bcc = EXTRACT_LE_16BITS(data1);
ND_PRINT((ndo, "smb_bcc=%u\n", bcc));
if (bcc > 0) {
smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr);
if (strcmp((const char *)(data1 + 2), "\\MAILSLOT\\BROWSE") == 0) {
print_browse(ndo, param, paramlen, data, datalen);
return;
}
if (strcmp((const char *)(data1 + 2), "\\PIPE\\LANMAN") == 0) {
print_ipc(ndo, param, paramlen, data, datalen);
return;
}
if (paramlen)
smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr);
if (datalen)
smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr);
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
|
CWE-125
| 182,987 | 4,164 |
290096538158812770757922067476373360557
| null | null | null |
tcpdump
|
af2cf04a9394c1a56227c2289ae8da262828294a
| 1 |
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;
}
|
CWE-674
| 182,988 | 4,165 |
5230270584618741121524521841493206479
| null | null | null |
tcpdump
|
13d52e9c0e7caf7e6325b0051bc90a49968be67f
| 1 |
bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
ND_TCHECK2(tptr[0], 5);
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
tlen = len;
while (tlen >= 3) {
ND_TCHECK2(tptr[0], 3);
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
tptr += 3;
tlen -= 3;
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
if (length < 3)
goto trunc;
length -= 3;
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length);
switch (type) {
case BGP_AIGP_TLV:
if (length < 8)
goto trunc;
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr,"\n\t ", length);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
|
CWE-125
| 182,990 | 4,167 |
338883693916013383552708360639081773443
| null | null | null |
tcpdump
|
211124b972e74f0da66bc8b16f181f78793e2f66
| 1 |
static int dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen)
{
uint8_t optlen, i;
ND_TCHECK(*option);
if (*option >= 32) {
ND_TCHECK(*(option+1));
optlen = *(option +1);
if (optlen < 2) {
if (*option >= 128)
ND_PRINT((ndo, "CCID option %u optlen too short", *option));
else
ND_PRINT((ndo, "%s optlen too short",
tok2str(dccp_option_values, "Option %u", *option)));
return 0;
}
} else
optlen = 1;
if (hlen < optlen) {
if (*option >= 128)
ND_PRINT((ndo, "CCID option %u optlen goes past header length",
*option));
else
ND_PRINT((ndo, "%s optlen goes past header length",
tok2str(dccp_option_values, "Option %u", *option)));
return 0;
}
ND_TCHECK2(*option, optlen);
if (*option >= 128) {
ND_PRINT((ndo, "CCID option %d", *option));
switch (optlen) {
case 4:
ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2)));
break;
case 6:
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
break;
default:
break;
}
} else {
ND_PRINT((ndo, "%s", tok2str(dccp_option_values, "Option %u", *option)));
switch (*option) {
case 32:
case 33:
case 34:
case 35:
if (optlen < 3) {
ND_PRINT((ndo, " optlen too short"));
return optlen;
}
if (*(option + 2) < 10){
ND_PRINT((ndo, " %s", dccp_feature_nums[*(option + 2)]));
for (i = 0; i < optlen - 3; i++)
ND_PRINT((ndo, " %d", *(option + 3 + i)));
}
break;
case 36:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 37:
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, " %d", *(option + 2 + i)));
break;
case 38:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 39:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 40:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 41:
if (optlen == 4)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else
ND_PRINT((ndo, " optlen != 4"));
break;
case 42:
if (optlen == 4)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else
ND_PRINT((ndo, " optlen != 4"));
break;
case 43:
if (optlen == 6)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else if (optlen == 4)
ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2)));
else
ND_PRINT((ndo, " optlen != 4 or 6"));
break;
case 44:
if (optlen > 2) {
ND_PRINT((ndo, " "));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
}
}
return optlen;
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
|
CWE-125
| 182,991 | 4,168 |
15798034750616692624256501172776322567
| null | null | null |
tcpdump
|
4846b3c5d0a850e860baf4f07340495d29837d09
| 1 |
ieee802_11_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int orig_caplen, int pad,
u_int fcslen)
{
uint16_t fc;
u_int caplen, hdrlen, meshdrlen;
struct lladdr_info src, dst;
int llc_hdrlen;
caplen = orig_caplen;
/* Remove FCS, if present */
if (length < fcslen) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
length -= fcslen;
if (caplen > length) {
/* Amount of FCS in actual packet data, if any */
fcslen = caplen - length;
caplen -= fcslen;
ndo->ndo_snapend -= fcslen;
}
if (caplen < IEEE802_11_FC_LEN) {
ND_PRINT((ndo, "%s", tstr));
return orig_caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(ndo, fc);
if (hdrlen == 0) {
/* Unknown frame type or control frame subtype; quit. */
return (0);
}
if (pad)
hdrlen = roundup2(hdrlen, 4);
if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA &&
DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) {
meshdrlen = extract_mesh_header_length(p+hdrlen);
hdrlen += meshdrlen;
} else
meshdrlen = 0;
if (caplen < hdrlen) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
if (ndo->ndo_eflag)
ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen);
/*
* Go past the 802.11 header.
*/
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
src.addr_string = etheraddr_string;
dst.addr_string = etheraddr_string;
switch (FC_TYPE(fc)) {
case T_MGMT:
get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr);
if (!mgmt_body_print(ndo, fc, src.addr, p, length)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_CTRL:
if (!ctrl_body_print(ndo, fc, p - hdrlen)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_DATA:
if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc)))
return hdrlen; /* no-data frame */
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc)) {
ND_PRINT((ndo, "Data"));
if (!wep_print(ndo, p)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
} else {
get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr);
llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst);
if (llc_hdrlen < 0) {
/*
* Some kinds of LLC packet we cannot
* handle intelligently
*/
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
llc_hdrlen = -llc_hdrlen;
}
hdrlen += llc_hdrlen;
}
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
return hdrlen;
}
|
CWE-125
| 182,993 | 4,169 |
36678721672009149185769722267742975874
| null | null | null |
tcpdump
|
e01c9bf76740802025c9328901b55ee4a0c49ed6
| 1 |
ospf6_print_lshdr(netdissect_options *ndo,
register const struct lsa6_hdr *lshp, const u_char *dataend)
{
if ((const u_char *)(lshp + 1) > dataend)
goto trunc;
ND_TCHECK(lshp->ls_type);
ND_TCHECK(lshp->ls_seq);
ND_PRINT((ndo, "\n\t Advertising Router %s, seq 0x%08x, age %us, length %u",
ipaddr_string(ndo, &lshp->ls_router),
EXTRACT_32BITS(&lshp->ls_seq),
EXTRACT_16BITS(&lshp->ls_age),
EXTRACT_16BITS(&lshp->ls_length)-(u_int)sizeof(struct lsa6_hdr)));
ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lshp->ls_type), &lshp->ls_stateid);
return (0);
trunc:
return (1);
}
|
CWE-125
| 183,006 | 4,181 |
129283399906377133502763174648763396470
| null | null | null |
tcpdump
|
9ba91381954ad325ea4fd26b9c65a8bd9a2a85b6
| 1 |
get_next_file(FILE *VFile, char *ptr)
{
char *ret;
ret = fgets(ptr, PATH_MAX, VFile);
if (!ret)
return NULL;
if (ptr[strlen(ptr) - 1] == '\n')
ptr[strlen(ptr) - 1] = '\0';
return ret;
}
|
CWE-120
| 183,007 | 4,182 |
257347123511778774923945109900514446221
| null | null | null |
libjpeg-turbo
|
9c78a04df4e44ef6487eee99c4258397f4fdca55
| 1 |
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;
}
|
CWE-125
| 183,008 | 4,183 |
167548316555997973400324006909003386736
| null | null | null |
tcpdump
|
12f66f69f7bf1ec1266ddbee90a7616cbf33696b
| 1 |
babel_print_v2(netdissect_options *ndo,
const u_char *cp, u_int length)
{
u_int i;
u_short bodylen;
u_char v4_prefix[16] =
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0 };
u_char v6_prefix[16] = {0};
ND_TCHECK2(*cp, 4);
if (length < 4)
goto invalid;
bodylen = EXTRACT_16BITS(cp + 2);
ND_PRINT((ndo, " (%u)", bodylen));
/* Process the TLVs in the body */
i = 0;
while(i < bodylen) {
const u_char *message;
u_int type, len;
message = cp + 4 + i;
ND_TCHECK2(*message, 1);
if((type = message[0]) == MESSAGE_PAD1) {
ND_PRINT((ndo, ndo->ndo_vflag ? "\n\tPad 1" : " pad1"));
i += 1;
continue;
}
ND_TCHECK2(*message, 2);
ICHECK(i, 2);
len = message[1];
ND_TCHECK2(*message, 2 + len);
ICHECK(i, 2 + len);
switch(type) {
case MESSAGE_PADN: {
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " padN"));
else
ND_PRINT((ndo, "\n\tPad %d", len + 2));
}
break;
case MESSAGE_ACK_REQ: {
u_short nonce, interval;
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " ack-req"));
else {
ND_PRINT((ndo, "\n\tAcknowledgment Request "));
if(len < 6) goto invalid;
nonce = EXTRACT_16BITS(message + 4);
interval = EXTRACT_16BITS(message + 6);
ND_PRINT((ndo, "%04x %s", nonce, format_interval(interval)));
}
}
break;
case MESSAGE_ACK: {
u_short nonce;
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " ack"));
else {
ND_PRINT((ndo, "\n\tAcknowledgment "));
if(len < 2) goto invalid;
nonce = EXTRACT_16BITS(message + 2);
ND_PRINT((ndo, "%04x", nonce));
}
}
break;
case MESSAGE_HELLO: {
u_short seqno, interval;
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " hello"));
else {
ND_PRINT((ndo, "\n\tHello "));
if(len < 6) goto invalid;
seqno = EXTRACT_16BITS(message + 4);
interval = EXTRACT_16BITS(message + 6);
ND_PRINT((ndo, "seqno %u interval %s", seqno, format_interval(interval)));
/* Extra data. */
if(len > 6)
subtlvs_print(ndo, message + 8, message + 2 + len, type);
}
}
break;
case MESSAGE_IHU: {
unsigned short txcost, interval;
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " ihu"));
else {
u_char address[16];
int rc;
ND_PRINT((ndo, "\n\tIHU "));
if(len < 6) goto invalid;
txcost = EXTRACT_16BITS(message + 4);
interval = EXTRACT_16BITS(message + 6);
rc = network_address(message[2], message + 8, len - 6, address);
if(rc < 0) { ND_PRINT((ndo, "%s", tstr)); break; }
ND_PRINT((ndo, "%s txcost %u interval %s",
format_address(ndo, address), txcost, format_interval(interval)));
/* Extra data. */
if((u_int)rc < len - 6)
subtlvs_print(ndo, message + 8 + rc, message + 2 + len,
type);
}
}
break;
case MESSAGE_ROUTER_ID: {
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " router-id"));
else {
ND_PRINT((ndo, "\n\tRouter Id"));
if(len < 10) goto invalid;
ND_PRINT((ndo, " %s", format_id(message + 4)));
}
}
break;
case MESSAGE_NH: {
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " nh"));
else {
int rc;
u_char nh[16];
ND_PRINT((ndo, "\n\tNext Hop"));
if(len < 2) goto invalid;
rc = network_address(message[2], message + 4, len - 2, nh);
if(rc < 0) goto invalid;
ND_PRINT((ndo, " %s", format_address(ndo, nh)));
}
}
break;
case MESSAGE_UPDATE: {
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, " update"));
if(len < 1)
ND_PRINT((ndo, "/truncated"));
else
ND_PRINT((ndo, "%s%s%s",
(message[3] & 0x80) ? "/prefix": "",
(message[3] & 0x40) ? "/id" : "",
(message[3] & 0x3f) ? "/unknown" : ""));
} else {
u_short interval, seqno, metric;
u_char plen;
int rc;
u_char prefix[16];
ND_PRINT((ndo, "\n\tUpdate"));
if(len < 10) goto invalid;
plen = message[4] + (message[2] == 1 ? 96 : 0);
rc = network_prefix(message[2], message[4], message[5],
message + 12,
message[2] == 1 ? v4_prefix : v6_prefix,
len - 10, prefix);
if(rc < 0) goto invalid;
interval = EXTRACT_16BITS(message + 6);
seqno = EXTRACT_16BITS(message + 8);
metric = EXTRACT_16BITS(message + 10);
ND_PRINT((ndo, "%s%s%s %s metric %u seqno %u interval %s",
(message[3] & 0x80) ? "/prefix": "",
(message[3] & 0x40) ? "/id" : "",
(message[3] & 0x3f) ? "/unknown" : "",
format_prefix(ndo, prefix, plen),
metric, seqno, format_interval_update(interval)));
if(message[3] & 0x80) {
if(message[2] == 1)
memcpy(v4_prefix, prefix, 16);
else
memcpy(v6_prefix, prefix, 16);
}
/* extra data? */
if((u_int)rc < len - 10)
subtlvs_print(ndo, message + 12 + rc, message + 2 + len, type);
}
}
break;
case MESSAGE_REQUEST: {
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " request"));
else {
int rc;
u_char prefix[16], plen;
ND_PRINT((ndo, "\n\tRequest "));
if(len < 2) goto invalid;
plen = message[3] + (message[2] == 1 ? 96 : 0);
rc = network_prefix(message[2], message[3], 0,
message + 4, NULL, len - 2, prefix);
if(rc < 0) goto invalid;
ND_PRINT((ndo, "for %s",
message[2] == 0 ? "any" : format_prefix(ndo, prefix, plen)));
}
}
break;
case MESSAGE_MH_REQUEST : {
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " mh-request"));
else {
int rc;
u_short seqno;
u_char prefix[16], plen;
ND_PRINT((ndo, "\n\tMH-Request "));
if(len < 14) goto invalid;
seqno = EXTRACT_16BITS(message + 4);
rc = network_prefix(message[2], message[3], 0,
message + 16, NULL, len - 14, prefix);
if(rc < 0) goto invalid;
plen = message[3] + (message[2] == 1 ? 96 : 0);
ND_PRINT((ndo, "(%u hops) for %s seqno %u id %s",
message[6], format_prefix(ndo, prefix, plen),
seqno, format_id(message + 8)));
}
}
break;
case MESSAGE_TSPC :
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " tspc"));
else {
ND_PRINT((ndo, "\n\tTS/PC "));
if(len < 6) goto invalid;
ND_PRINT((ndo, "timestamp %u packetcounter %u", EXTRACT_32BITS (message + 4),
EXTRACT_16BITS(message + 2)));
}
break;
case MESSAGE_HMAC : {
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " hmac"));
else {
unsigned j;
ND_PRINT((ndo, "\n\tHMAC "));
if(len < 18) goto invalid;
ND_PRINT((ndo, "key-id %u digest-%u ", EXTRACT_16BITS(message + 2), len - 2));
for (j = 0; j < len - 2; j++)
ND_PRINT((ndo, "%02X", message[4 + j]));
}
}
break;
case MESSAGE_UPDATE_SRC_SPECIFIC : {
if(!ndo->ndo_vflag) {
ND_PRINT((ndo, " ss-update"));
} else {
u_char prefix[16], src_prefix[16];
u_short interval, seqno, metric;
u_char ae, plen, src_plen, omitted;
int rc;
int parsed_len = 10;
ND_PRINT((ndo, "\n\tSS-Update"));
if(len < 10) goto invalid;
ae = message[2];
src_plen = message[3];
plen = message[4];
omitted = message[5];
interval = EXTRACT_16BITS(message + 6);
seqno = EXTRACT_16BITS(message + 8);
metric = EXTRACT_16BITS(message + 10);
rc = network_prefix(ae, plen, omitted, message + 2 + parsed_len,
ae == 1 ? v4_prefix : v6_prefix,
len - parsed_len, prefix);
if(rc < 0) goto invalid;
if(ae == 1)
plen += 96;
parsed_len += rc;
rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len,
NULL, len - parsed_len, src_prefix);
if(rc < 0) goto invalid;
if(ae == 1)
src_plen += 96;
parsed_len += rc;
ND_PRINT((ndo, " %s from", format_prefix(ndo, prefix, plen)));
ND_PRINT((ndo, " %s metric %u seqno %u interval %s",
format_prefix(ndo, src_prefix, src_plen),
metric, seqno, format_interval_update(interval)));
/* extra data? */
if((u_int)parsed_len < len)
subtlvs_print(ndo, message + 2 + parsed_len,
message + 2 + len, type);
}
}
break;
case MESSAGE_REQUEST_SRC_SPECIFIC : {
if(!ndo->ndo_vflag)
ND_PRINT((ndo, " ss-request"));
else {
int rc, parsed_len = 3;
u_char ae, plen, src_plen, prefix[16], src_prefix[16];
ND_PRINT((ndo, "\n\tSS-Request "));
if(len < 3) goto invalid;
ae = message[2];
plen = message[3];
src_plen = message[4];
rc = network_prefix(ae, plen, 0, message + 2 + parsed_len,
NULL, len - parsed_len, prefix);
if(rc < 0) goto invalid;
if(ae == 1)
plen += 96;
parsed_len += rc;
rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len,
NULL, len - parsed_len, src_prefix);
if(rc < 0) goto invalid;
if(ae == 1)
src_plen += 96;
parsed_len += rc;
if(ae == 0) {
ND_PRINT((ndo, "for any"));
} else {
ND_PRINT((ndo, "for (%s, ", format_prefix(ndo, prefix, plen)));
ND_PRINT((ndo, "%s)", format_prefix(ndo, src_prefix, src_plen)));
}
}
}
break;
case MESSAGE_MH_REQUEST_SRC_SPECIFIC : {
if(!ndo->ndo_vflag)
ND_PRINT((ndo, " ss-mh-request"));
else {
int rc, parsed_len = 14;
u_short seqno;
u_char ae, plen, src_plen, prefix[16], src_prefix[16], hopc;
const u_char *router_id = NULL;
ND_PRINT((ndo, "\n\tSS-MH-Request "));
if(len < 14) goto invalid;
ae = message[2];
plen = message[3];
seqno = EXTRACT_16BITS(message + 4);
hopc = message[6];
src_plen = message[7];
router_id = message + 8;
rc = network_prefix(ae, plen, 0, message + 2 + parsed_len,
NULL, len - parsed_len, prefix);
if(rc < 0) goto invalid;
if(ae == 1)
plen += 96;
parsed_len += rc;
rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len,
NULL, len - parsed_len, src_prefix);
if(rc < 0) goto invalid;
if(ae == 1)
src_plen += 96;
ND_PRINT((ndo, "(%u hops) for (%s, ",
hopc, format_prefix(ndo, prefix, plen)));
ND_PRINT((ndo, "%s) seqno %u id %s",
format_prefix(ndo, src_prefix, src_plen),
seqno, format_id(router_id)));
}
}
break;
default:
if (!ndo->ndo_vflag)
ND_PRINT((ndo, " unknown"));
else
ND_PRINT((ndo, "\n\tUnknown message type %d", type));
}
i += len + 2;
}
return;
trunc:
ND_PRINT((ndo, " %s", tstr));
return;
invalid:
ND_PRINT((ndo, "%s", istr));
return;
}
|
CWE-125
| 183,013 | 4,187 |
221650779211644088946090247874179905863
| null | null | null |
tcpdump
|
396e94ff55a80d554b1fe46bf107db1e91008d6c
| 1 |
ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
ND_PRINT((ndo," attrs=("));
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
if (cp == NULL) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo," status=("));
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
ND_PRINT((ndo,")"));
break;
default:
/*
* XXX - fill in more types here; see, for example,
* draft-ietf-ipsec-notifymsg-04.
*/
if (ndo->ndo_vflag > 3) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
break;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
|
CWE-125
| 183,014 | 4,188 |
234740568020028654327916497265826086872
| null | null | null |
tcpdump
|
aa3e54f594385ce7e1e319b0c84999e51192578b
| 1 |
mfr_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
u_int tlen,idx,hdr_len = 0;
uint16_t sequence_num;
uint8_t ie_type,ie_len;
const uint8_t *tptr;
/*
* FRF.16 Link Integrity Control Frame
*
* 7 6 5 4 3 2 1 0
* +----+----+----+----+----+----+----+----+
* | B | E | C=1| 0 0 0 0 | EA |
* +----+----+----+----+----+----+----+----+
* | 0 0 0 0 0 0 0 0 |
* +----+----+----+----+----+----+----+----+
* | message type |
* +----+----+----+----+----+----+----+----+
*/
ND_TCHECK2(*p, 4); /* minimum frame header length */
if ((p[0] & MFR_BEC_MASK) == MFR_CTRL_FRAME && p[1] == 0) {
ND_PRINT((ndo, "FRF.16 Control, Flags [%s], %s, length %u",
bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK)),
tok2str(mfr_ctrl_msg_values,"Unknown Message (0x%02x)",p[2]),
length));
tptr = p + 3;
tlen = length -3;
hdr_len = 3;
if (!ndo->ndo_vflag)
return hdr_len;
while (tlen>sizeof(struct ie_tlv_header_t)) {
ND_TCHECK2(*tptr, sizeof(struct ie_tlv_header_t));
ie_type=tptr[0];
ie_len=tptr[1];
ND_PRINT((ndo, "\n\tIE %s (%u), length %u: ",
tok2str(mfr_ctrl_ie_values,"Unknown",ie_type),
ie_type,
ie_len));
/* infinite loop check */
if (ie_type == 0 || ie_len <= sizeof(struct ie_tlv_header_t))
return hdr_len;
ND_TCHECK2(*tptr, ie_len);
tptr+=sizeof(struct ie_tlv_header_t);
/* tlv len includes header */
ie_len-=sizeof(struct ie_tlv_header_t);
tlen-=sizeof(struct ie_tlv_header_t);
switch (ie_type) {
case MFR_CTRL_IE_MAGIC_NUM:
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(tptr)));
break;
case MFR_CTRL_IE_BUNDLE_ID: /* same message format */
case MFR_CTRL_IE_LINK_ID:
for (idx = 0; idx < ie_len && idx < MFR_ID_STRING_MAXLEN; idx++) {
if (*(tptr+idx) != 0) /* don't print null termination */
safeputchar(ndo, *(tptr + idx));
else
break;
}
break;
case MFR_CTRL_IE_TIMESTAMP:
if (ie_len == sizeof(struct timeval)) {
ts_print(ndo, (const struct timeval *)tptr);
break;
}
/* fall through and hexdump if no unix timestamp */
/*
* FIXME those are the defined IEs that lack a decoder
* you are welcome to contribute code ;-)
*/
case MFR_CTRL_IE_VENDOR_EXT:
case MFR_CTRL_IE_CAUSE:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", ie_len);
break;
}
/* do we want to see a hexdump of the IE ? */
if (ndo->ndo_vflag > 1 )
print_unknown_data(ndo, tptr, "\n\t ", ie_len);
tlen-=ie_len;
tptr+=ie_len;
}
return hdr_len;
}
/*
* FRF.16 Fragmentation Frame
*
* 7 6 5 4 3 2 1 0
* +----+----+----+----+----+----+----+----+
* | B | E | C=0|seq. (high 4 bits) | EA |
* +----+----+----+----+----+----+----+----+
* | sequence (low 8 bits) |
* +----+----+----+----+----+----+----+----+
* | DLCI (6 bits) | CR | EA |
* +----+----+----+----+----+----+----+----+
* | DLCI (4 bits) |FECN|BECN| DE | EA |
* +----+----+----+----+----+----+----+----+
*/
sequence_num = (p[0]&0x1e)<<7 | p[1];
/* whole packet or first fragment ? */
if ((p[0] & MFR_BEC_MASK) == MFR_FRAG_FRAME ||
(p[0] & MFR_BEC_MASK) == MFR_B_BIT) {
ND_PRINT((ndo, "FRF.16 Frag, seq %u, Flags [%s], ",
sequence_num,
bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK))));
hdr_len = 2;
fr_print(ndo, p+hdr_len,length-hdr_len);
return hdr_len;
}
/* must be a middle or the last fragment */
ND_PRINT((ndo, "FRF.16 Frag, seq %u, Flags [%s]",
sequence_num,
bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK))));
print_unknown_data(ndo, p, "\n\t", length);
return hdr_len;
trunc:
ND_PRINT((ndo, "[|mfr]"));
return length;
}
|
CWE-125
| 183,015 | 4,189 |
34406534537232211407707148522224410637
| null | null | null |
tcpdump
|
e3f3b445e2d20ac5d5b7fcb7559ce6beb55da0c9
| 1 |
bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
/* Restart Flags (4 bits), Restart Time in seconds (12 bits) */
ND_TCHECK_16BITS(opt + i + 2);
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
|
CWE-125
| 183,016 | 4,190 |
48898273469995462417668997058690739974
| null | null | null |
tcpdump
|
c24922e692a52121e853a84ead6b9337f4c08a94
| 1 |
rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport,
int32_t *opcode)
{
int i;
struct rx_cache_entry *rxent;
uint32_t clip;
uint32_t sip;
UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t));
UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t));
/* Start the search where we last left off */
i = rx_cache_hint;
do {
rxent = &rx_cache[i];
if (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) &&
rxent->client.s_addr == clip &&
rxent->server.s_addr == sip &&
rxent->serviceId == EXTRACT_32BITS(&rxh->serviceId) &&
rxent->dport == sport) {
/* We got a match! */
rx_cache_hint = i;
*opcode = rxent->opcode;
return(1);
}
if (++i >= RX_CACHE_SIZE)
i = 0;
} while (i != rx_cache_hint);
/* Our search failed */
return(0);
}
|
CWE-125
| 183,017 | 4,191 |
103259589506430565932165256731066864554
| null | null | null |
tcpdump
|
bea2686c296b79609060a104cc139810785b0739
| 1 |
rsvp_obj_print(netdissect_options *ndo,
const u_char *pptr, u_int plen, const u_char *tptr,
const char *ident, u_int tlen,
const struct rsvp_common_header *rsvp_com_header)
{
const struct rsvp_object_header *rsvp_obj_header;
const u_char *obj_tptr;
union {
const struct rsvp_obj_integrity_t *rsvp_obj_integrity;
const struct rsvp_obj_frr_t *rsvp_obj_frr;
} obj_ptr;
u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;
int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;
union {
float f;
uint32_t i;
} bw;
uint8_t namelen;
u_int action, subchannel;
while(tlen>=sizeof(struct rsvp_object_header)) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));
rsvp_obj_header = (const struct rsvp_object_header *)tptr;
rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);
rsvp_obj_ctype=rsvp_obj_header->ctype;
if(rsvp_obj_len % 4) {
ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len));
return -1;
}
if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {
ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len,
(unsigned long)sizeof(const struct rsvp_object_header)));
return -1;
}
ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s",
ident,
tok2str(rsvp_obj_values,
"Unknown",
rsvp_obj_header->class_num),
rsvp_obj_header->class_num,
((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject"));
if (rsvp_obj_header->class_num > 128)
ND_PRINT((ndo, " %s",
((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently"));
ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u",
tok2str(rsvp_ctype_values,
"Unknown",
((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),
rsvp_obj_ctype,
rsvp_obj_len));
if(tlen < rsvp_obj_len) {
ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident));
return -1;
}
obj_tptr=tptr+sizeof(struct rsvp_object_header);
obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);
/* did we capture enough for fully decoding the object ? */
if (!ND_TTEST2(*tptr, rsvp_obj_len))
return -1;
hexdump=FALSE;
switch(rsvp_obj_header->class_num) {
case RSVP_OBJ_SESSION:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return -1;
ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+5),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return -1;
ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in6_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+sizeof(struct in6_addr)+1),
EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 36)
return -1;
ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ip6addr_string(ndo, obj_tptr + 20)));
obj_tlen-=36;
obj_tptr+=36;
break;
case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */
if (obj_tlen < 26)
return -1;
ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ip6addr_string(ndo, obj_tptr + 8)));
obj_tlen-=26;
obj_tptr+=26;
break;
case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
case RSVP_CTYPE_UNI_IPV4:
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CONFIRM:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Receiver Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return -1;
ND_PRINT((ndo, "%s IPv6 Receiver Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_NOTIFY_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return-1;
ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */
case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */
case RSVP_OBJ_RECOVERY_LABEL: /* fall through */
case RSVP_OBJ_LABEL:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Generalized Label: %u",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u",
ident,
EXTRACT_32BITS(obj_tptr),
ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_STYLE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]",
ident,
tok2str(rsvp_resstyle_values,
"Unknown",
EXTRACT_24BITS(obj_tptr+1)),
*(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SENDER_TEMPLATE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" ));
ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+4))&0xfff,
(EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));
ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+8))&0xfff,
(EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI",
ident,
(EXTRACT_32BITS(obj_tptr+4))&0x7fffff,
(EXTRACT_32BITS(obj_tptr+8))&0x7fffff,
(((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "",
(((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : ""));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)",
ident,
tok2str(gmpls_encoding_values,
"Unknown",
*obj_tptr),
*obj_tptr));
ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)",
ident,
tok2str(gmpls_switch_cap_values,
"Unknown",
*(obj_tptr+1)),
*(obj_tptr+1),
tok2str(gmpls_payload_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+2)),
EXTRACT_16BITS(obj_tptr + 2)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RRO:
case RSVP_OBJ_ERO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
while(obj_tlen >= 4 ) {
u_char length;
ND_TCHECK2(*obj_tptr, 4);
length = *(obj_tptr + 1);
ND_PRINT((ndo, "%s Subobject Type: %s, length %u",
ident,
tok2str(rsvp_obj_xro_values,
"Unknown %u",
RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),
length));
if (length == 0) { /* prevent infinite loops */
ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident));
break;
}
switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {
u_char prefix_length;
case RSVP_OBJ_XRO_IPV4:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
prefix_length = *(obj_tptr+6);
if (prefix_length != 32) {
ND_PRINT((ndo, " ERROR: Prefix length %u != 32",
prefix_length));
goto invalid;
}
ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]",
RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict",
ipaddr_string(ndo, obj_tptr+2),
*(obj_tptr+6),
bittok2str(rsvp_obj_rro_flag_values,
"none",
*(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */
break;
case RSVP_OBJ_XRO_LABEL:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u",
bittok2str(rsvp_obj_rro_label_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr+2),
tok2str(rsvp_ctype_values,
"Unknown",
*(obj_tptr+3) + 256*RSVP_OBJ_RRO),
*(obj_tptr+3),
EXTRACT_32BITS(obj_tptr + 4)));
}
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_HELLO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RESTART_CAPABILITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SESSION_ATTRIBUTE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 4)
return-1;
namelen = *(obj_tptr+3);
if (obj_tlen < 4+namelen)
return-1;
ND_PRINT((ndo, "%s Session Name: ", ident));
for (i = 0; i < namelen; i++)
safeputchar(ndo, *(obj_tptr + 4 + i));
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)",
ident,
(int)*obj_tptr,
(int)*(obj_tptr+1),
bittok2str(rsvp_session_attribute_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr + 2)));
obj_tlen-=4+*(obj_tptr+3);
obj_tptr+=4+*(obj_tptr+3);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_GENERALIZED_UNI:
switch(rsvp_obj_ctype) {
int subobj_type,af,subobj_len,total_subobj_len;
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
/* read variable length subobjects */
total_subobj_len = obj_tlen;
while(total_subobj_len > 0) {
/* If RFC 3476 Section 3.1 defined that a sub-object of the
* GENERALIZED_UNI RSVP object must have the Length field as
* a multiple of 4, instead of the check below it would be
* better to test total_subobj_len only once before the loop.
* So long as it does not define it and this while loop does
* not implement such a requirement, let's accept that within
* each iteration subobj_len may happen to be a multiple of 1
* and test it and total_subobj_len respectively.
*/
if (total_subobj_len < 4)
goto invalid;
subobj_len = EXTRACT_16BITS(obj_tptr);
subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;
af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;
ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u",
ident,
tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type),
subobj_type,
tok2str(af_values, "Unknown", af), af,
subobj_len));
/* In addition to what is explained above, the same spec does not
* explicitly say that the same Length field includes the 4-octet
* sub-object header, but as long as this while loop implements it
* as it does include, let's keep the check below consistent with
* the rest of the code.
*/
if(subobj_len < 4 || subobj_len > total_subobj_len)
goto invalid;
switch(subobj_type) {
case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:
case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:
switch(af) {
case AFNUM_INET:
if (subobj_len < 8)
return -1;
ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s",
ident, ipaddr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_INET6:
if (subobj_len < 20)
return -1;
ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s",
ident, ip6addr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_NSAP:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
}
break;
case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:
if (subobj_len < 16) {
return -1;
}
ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u",
ident,
((EXTRACT_32BITS(obj_tptr+4))>>31),
((EXTRACT_32BITS(obj_tptr+4))&0xFF),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr + 12)));
break;
case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:
if (subobj_len < 8) {
return -1;
}
ND_PRINT((ndo, "%s Service level: %u",
ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));
break;
default:
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
obj_tptr+=subobj_len;
obj_tlen+=subobj_len;
}
if (total_subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RSVP_HOP:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
if (obj_tlen)
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 16)));
obj_tlen-=20;
obj_tptr+=20;
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_TIME_VALUES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Refresh Period: %ums",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
/* those three objects do share the same semantics */
case RSVP_OBJ_SENDER_TSPEC:
case RSVP_OBJ_ADSPEC:
case RSVP_OBJ_FLOWSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Msg-Version: %u, length: %u",
ident,
(*obj_tptr & 0xf0) >> 4,
EXTRACT_16BITS(obj_tptr + 2) << 2));
obj_tptr+=4; /* get to the start of the service header */
obj_tlen-=4;
while (obj_tlen >= 4) {
intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;
ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u",
ident,
tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)),
*(obj_tptr),
(*(obj_tptr+1)&0x80) ? "" : "not",
intserv_serv_tlen));
obj_tptr+=4; /* get to the start of the parameter list */
obj_tlen-=4;
while (intserv_serv_tlen>=4) {
processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);
if (processed == 0)
break;
obj_tlen-=processed;
intserv_serv_tlen-=processed;
obj_tptr+=processed;
}
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FILTERSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_24BITS(obj_tptr + 17)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FASTREROUTE:
/* the differences between c-type 1 and 7 are minor */
obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1: /* new style */
if (obj_tlen < sizeof(struct rsvp_obj_frr_t))
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all)));
obj_tlen-=sizeof(struct rsvp_obj_frr_t);
obj_tptr+=sizeof(struct rsvp_obj_frr_t);
break;
case RSVP_CTYPE_TUNNEL_IPV4: /* old style */
if (obj_tlen < 16)
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_DETOUR:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
while(obj_tlen >= 8) {
ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
ipaddr_string(ndo, obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CLASSTYPE:
case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
ND_PRINT((ndo, "%s CT: %u",
ident,
EXTRACT_32BITS(obj_tptr) & 0x7));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ERROR_SPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
error_code=*(obj_tptr+5);
error_value=EXTRACT_16BITS(obj_tptr+6);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr+4),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value),
error_value));
break;
default:
ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value));
break;
}
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
error_code=*(obj_tptr+17);
error_value=EXTRACT_16BITS(obj_tptr+18);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr+16),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
default:
break;
}
obj_tlen-=20;
obj_tptr+=20;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_PROPERTIES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
padbytes = EXTRACT_16BITS(obj_tptr+2);
ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u",
ident,
EXTRACT_16BITS(obj_tptr),
padbytes));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there is anything longer than the TLV header (2) */
while(obj_tlen >= 2 + padbytes) {
ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */
ident,
tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr),
*obj_tptr,
*(obj_tptr + 1)));
if (obj_tlen < *(obj_tptr+1))
return-1;
if (*(obj_tptr+1) < 2)
return -1;
print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2);
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_MESSAGE_ID: /* fall through */
case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */
case RSVP_OBJ_MESSAGE_ID_LIST:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u",
ident,
*obj_tptr,
EXTRACT_24BITS(obj_tptr + 1)));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there are no messages left */
while(obj_tlen >= 4) {
ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_INTEGRITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))
return-1;
obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;
ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]",
ident,
EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),
bittok2str(rsvp_obj_integrity_flag_values,
"none",
obj_ptr.rsvp_obj_integrity->flags)));
ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));
sigcheck = signature_verify(ndo, pptr, plen,
obj_ptr.rsvp_obj_integrity->digest,
rsvp_clear_checksum,
rsvp_com_header);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
obj_tlen+=sizeof(struct rsvp_obj_integrity_t);
obj_tptr+=sizeof(struct rsvp_obj_integrity_t);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ADMIN_STATUS:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Flags [%s]", ident,
bittok2str(rsvp_obj_admin_status_flag_values, "none",
EXTRACT_32BITS(obj_tptr))));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_SET:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
action = (EXTRACT_16BITS(obj_tptr)>>8);
ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident,
tok2str(rsvp_obj_label_set_action_values, "Unknown", action),
action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));
switch (action) {
case LABEL_SET_INCLUSIVE_RANGE:
case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */
/* only a couple of subchannels are expected */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
obj_tlen-=4;
obj_tptr+=4;
subchannel = 1;
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel,
EXTRACT_32BITS(obj_tptr)));
obj_tptr+=4;
obj_tlen-=4;
subchannel++;
}
break;
}
break;
default:
hexdump=TRUE;
}
case RSVP_OBJ_S2L:
switch (rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ipaddr_string(ndo, obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ip6addr_string(ndo, obj_tptr)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case RSVP_OBJ_SCOPE:
case RSVP_OBJ_POLICY_DATA:
case RSVP_OBJ_ACCEPT_LABEL_SET:
case RSVP_OBJ_PROTECTION:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || hexdump == TRUE)
print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */
rsvp_obj_len - sizeof(struct rsvp_object_header));
tptr+=rsvp_obj_len;
tlen-=rsvp_obj_len;
}
return 0;
invalid:
ND_PRINT((ndo, "%s", istr));
return -1;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return -1;
}
|
CWE-125
| 183,019 | 4,192 |
337800776597343775473726240216962889776
| null | null | null |
tcpdump
|
d97e94223720684c6aa740ff219e0d19426c2220
| 1 |
lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr,
int total_subobj_len, int offset)
{
int hexdump = FALSE;
int subobj_type, subobj_len;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
while (total_subobj_len > 0 && hexdump == FALSE ) {
subobj_type = EXTRACT_8BITS(obj_tptr + offset);
subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1);
ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u",
tok2str(lmp_data_link_subobj,
"Unknown",
subobj_type),
subobj_type,
subobj_len));
if (subobj_len < 4) {
ND_PRINT((ndo, " (too short)"));
break;
}
if ((subobj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
break;
}
if (total_subobj_len < subobj_len) {
ND_PRINT((ndo, " (goes past the end of the object)"));
break;
}
switch(subobj_type) {
case INT_SWITCHING_TYPE_SUBOBJ:
ND_PRINT((ndo, "\n\t Switching Type: %s (%u)",
tok2str(gmpls_switch_cap_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 2)),
EXTRACT_8BITS(obj_tptr + offset + 2)));
ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)",
tok2str(gmpls_encoding_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 3)),
EXTRACT_8BITS(obj_tptr + offset + 3)));
bw.i = EXTRACT_32BITS(obj_tptr+offset+4);
ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
bw.i = EXTRACT_32BITS(obj_tptr+offset+8);
ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case WAVELENGTH_SUBOBJ:
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+offset+4)));
break;
default:
/* Any Unknown Subobject ==> Exit loop */
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
offset+=subobj_len;
}
return (hexdump);
}
|
CWE-125
| 183,021 | 4,194 |
251322797576181429768134457548704955599
| null | null | null |
tcpdump
|
3de07c772166b7e8e8bb4b9d1d078f1d901b570b
| 1 |
vrrp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len,
register const u_char *bp2, int ttl)
{
int version, type, auth_type = VRRP_AUTH_NONE; /* keep compiler happy */
const char *type_s;
ND_TCHECK(bp[0]);
version = (bp[0] & 0xf0) >> 4;
type = bp[0] & 0x0f;
type_s = tok2str(type2str, "unknown type (%u)", type);
ND_PRINT((ndo, "VRRPv%u, %s", version, type_s));
if (ttl != 255)
ND_PRINT((ndo, ", (ttl %u)", ttl));
if (version < 2 || version > 3 || type != VRRP_TYPE_ADVERTISEMENT)
return;
ND_TCHECK(bp[2]);
ND_PRINT((ndo, ", vrid %u, prio %u", bp[1], bp[2]));
ND_TCHECK(bp[5]);
if (version == 2) {
auth_type = bp[4];
ND_PRINT((ndo, ", authtype %s", tok2str(auth2str, NULL, auth_type)));
ND_PRINT((ndo, ", intvl %us, length %u", bp[5], len));
} else { /* version == 3 */
uint16_t intvl = (bp[4] & 0x0f) << 8 | bp[5];
ND_PRINT((ndo, ", intvl %ucs, length %u", intvl, len));
}
if (ndo->ndo_vflag) {
int naddrs = bp[3];
int i;
char c;
if (version == 2 && ND_TTEST2(bp[0], len)) {
struct cksum_vec vec[1];
vec[0].ptr = bp;
vec[0].len = len;
if (in_cksum(vec, 1))
ND_PRINT((ndo, ", (bad vrrp cksum %x)",
EXTRACT_16BITS(&bp[6])));
}
if (version == 3 && ND_TTEST2(bp[0], len)) {
uint16_t cksum = nextproto4_cksum(ndo, (const struct ip *)bp2, bp,
len, len, IPPROTO_VRRP);
if (cksum)
ND_PRINT((ndo, ", (bad vrrp cksum %x)",
EXTRACT_16BITS(&bp[6])));
}
ND_PRINT((ndo, ", addrs"));
if (naddrs > 1)
ND_PRINT((ndo, "(%d)", naddrs));
ND_PRINT((ndo, ":"));
c = ' ';
bp += 8;
for (i = 0; i < naddrs; i++) {
ND_TCHECK(bp[3]);
ND_PRINT((ndo, "%c%s", c, ipaddr_string(ndo, bp)));
c = ',';
bp += 4;
}
if (version == 2 && auth_type == VRRP_AUTH_SIMPLE) { /* simple text password */
ND_TCHECK(bp[7]);
ND_PRINT((ndo, " auth \""));
if (fn_printn(ndo, bp, 8, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
}
}
return;
trunc:
ND_PRINT((ndo, "[|vrrp]"));
}
|
CWE-125
| 183,022 | 4,195 |
177267562973387450052135539416313243713
| null | null | null |
tcpdump
|
1a1bce0526a77b62e41531b00f8bb5e21fd4f3a3
| 1 |
icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,
int fragmented)
{
char *cp;
const struct icmp *dp;
const struct icmp_ext_t *ext_dp;
const struct ip *ip;
const char *str, *fmt;
const struct ip *oip;
const struct udphdr *ouh;
const uint8_t *obj_tptr;
uint32_t raw_label;
const u_char *snapend_save;
const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;
u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;
char buf[MAXHOSTNAMELEN + 100];
struct cksum_vec vec[1];
dp = (const struct icmp *)bp;
ext_dp = (const struct icmp_ext_t *)bp;
ip = (const struct ip *)bp2;
str = buf;
ND_TCHECK(dp->icmp_code);
switch (dp->icmp_type) {
case ICMP_ECHO:
case ICMP_ECHOREPLY:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u",
dp->icmp_type == ICMP_ECHO ?
"request" : "reply",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_UNREACH:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_UNREACH_PROTOCOL:
ND_TCHECK(dp->icmp_ip.ip_p);
(void)snprintf(buf, sizeof(buf),
"%s protocol %d unreachable",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
dp->icmp_ip.ip_p);
break;
case ICMP_UNREACH_PORT:
ND_TCHECK(dp->icmp_ip.ip_p);
oip = &dp->icmp_ip;
hlen = IP_HL(oip) * 4;
ouh = (const struct udphdr *)(((const u_char *)oip) + hlen);
ND_TCHECK(ouh->uh_dport);
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (oip->ip_p) {
case IPPROTO_TCP:
(void)snprintf(buf, sizeof(buf),
"%s tcp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
tcpport_string(ndo, dport));
break;
case IPPROTO_UDP:
(void)snprintf(buf, sizeof(buf),
"%s udp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
udpport_string(ndo, dport));
break;
default:
(void)snprintf(buf, sizeof(buf),
"%s protocol %u port %u unreachable",
ipaddr_string(ndo, &oip->ip_dst),
oip->ip_p, dport);
break;
}
break;
case ICMP_UNREACH_NEEDFRAG:
{
register const struct mtu_discovery *mp;
mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;
mtu = EXTRACT_16BITS(&mp->nexthopmtu);
if (mtu) {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag (mtu %d)",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);
} else {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
}
}
break;
default:
fmt = tok2str(unreach2str, "#%d %%s unreachable",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
break;
}
break;
case ICMP_REDIRECT:
ND_TCHECK(dp->icmp_ip.ip_dst);
fmt = tok2str(type2str, "redirect-#%d %%s to net %%s",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
ipaddr_string(ndo, &dp->icmp_gwaddr));
break;
case ICMP_ROUTERADVERT:
{
register const struct ih_rdiscovery *ihp;
register const struct id_rdiscovery *idp;
u_int lifetime, num, size;
(void)snprintf(buf, sizeof(buf), "router advertisement");
cp = buf + strlen(buf);
ihp = (const struct ih_rdiscovery *)&dp->icmp_void;
ND_TCHECK(*ihp);
(void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf));
cp = buf + strlen(buf);
lifetime = EXTRACT_16BITS(&ihp->ird_lifetime);
if (lifetime < 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u",
lifetime);
} else if (lifetime < 60 * 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u",
lifetime / 60, lifetime % 60);
} else {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
"%u:%02u:%02u",
lifetime / 3600,
(lifetime % 3600) / 60,
lifetime % 60);
}
cp = buf + strlen(buf);
num = ihp->ird_addrnum;
(void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num);
cp = buf + strlen(buf);
size = ihp->ird_addrsiz;
if (size != 2) {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
" [size %d]", size);
break;
}
idp = (const struct id_rdiscovery *)&dp->icmp_data;
while (num-- > 0) {
ND_TCHECK(*idp);
(void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}",
ipaddr_string(ndo, &idp->ird_addr),
EXTRACT_32BITS(&idp->ird_pref));
cp = buf + strlen(buf);
++idp;
}
}
break;
case ICMP_TIMXCEED:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_TIMXCEED_INTRANS:
str = "time exceeded in-transit";
break;
case ICMP_TIMXCEED_REASS:
str = "ip reassembly time exceeded";
break;
default:
(void)snprintf(buf, sizeof(buf), "time exceeded-#%u",
dp->icmp_code);
break;
}
break;
case ICMP_PARAMPROB:
if (dp->icmp_code)
(void)snprintf(buf, sizeof(buf),
"parameter problem - code %u", dp->icmp_code);
else {
ND_TCHECK(dp->icmp_pptr);
(void)snprintf(buf, sizeof(buf),
"parameter problem - octet %u", dp->icmp_pptr);
}
break;
case ICMP_MASKREPLY:
ND_TCHECK(dp->icmp_mask);
(void)snprintf(buf, sizeof(buf), "address mask is 0x%08x",
EXTRACT_32BITS(&dp->icmp_mask));
break;
case ICMP_TSTAMP:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf),
"time stamp query id %u seq %u",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_TSTAMPREPLY:
ND_TCHECK(dp->icmp_ttime);
(void)snprintf(buf, sizeof(buf),
"time stamp reply id %u seq %u: org %s",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq),
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));
break;
default:
str = tok2str(icmp2str, "type-#%d", dp->icmp_type);
break;
}
ND_PRINT((ndo, "ICMP %s, length %u", str, plen));
if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */
if (ND_TTEST2(*bp, plen)) {
uint16_t sum;
vec[0].ptr = (const uint8_t *)(const void *)dp;
vec[0].len = plen;
sum = in_cksum(vec, 1);
if (sum != 0) {
uint16_t icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);
ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)",
icmp_sum,
in_cksum_shouldbe(icmp_sum, sum)));
}
}
}
/*
* print the remnants of the IP packet.
* save the snaplength as this may get overidden in the IP printer.
*/
if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {
bp += 8;
ND_PRINT((ndo, "\n\t"));
ip = (const struct ip *)bp;
ndo->ndo_snaplen = ndo->ndo_snapend - bp;
snapend_save = ndo->ndo_snapend;
ND_TCHECK_16BITS(&ip->ip_len);
ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));
ndo->ndo_snapend = snapend_save;
}
/*
* Attempt to decode the MPLS extensions only for some ICMP types.
*/
if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {
ND_TCHECK(*ext_dp);
/*
* Check first if the mpls extension header shows a non-zero length.
* If the length field is not set then silently verify the checksum
* to check if an extension header is present. This is expedient,
* however not all implementations set the length field proper.
*/
if (!ext_dp->icmp_length &&
ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = plen - ICMP_EXTD_MINLEN;
if (in_cksum(vec, 1)) {
return;
}
}
ND_PRINT((ndo, "\n\tMPLS extension v%u",
ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));
/*
* Sanity checking of the header.
*/
if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=
ICMP_MPLS_EXT_VERSION) {
ND_PRINT((ndo, " packet not supported"));
return;
}
hlen = plen - ICMP_EXTD_MINLEN;
if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = hlen;
ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u",
EXTRACT_16BITS(ext_dp->icmp_ext_checksum),
in_cksum(vec, 1) ? "in" : "",
hlen));
}
hlen -= 4; /* subtract common header size */
obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;
while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {
icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;
ND_TCHECK(*icmp_mpls_ext_object_header);
obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);
obj_class_num = icmp_mpls_ext_object_header->class_num;
obj_ctype = icmp_mpls_ext_object_header->ctype;
obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u",
tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num),
obj_class_num,
obj_ctype,
obj_tlen));
hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */
/* infinite loop protection */
if ((obj_class_num == 0) ||
(obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {
return;
}
obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);
switch (obj_class_num) {
case 1:
switch(obj_ctype) {
case 1:
ND_TCHECK2(*obj_tptr, 4);
raw_label = EXTRACT_32BITS(obj_tptr);
ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));
if (MPLS_STACK(raw_label))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label)));
break;
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case 2:
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
break;
}
if (hlen < obj_tlen)
break;
hlen -= obj_tlen;
obj_tptr += obj_tlen;
}
}
return;
trunc:
ND_PRINT((ndo, "[|icmp]"));
}
|
CWE-125
| 183,023 | 4,196 |
292921596680894319883034116174751358197
| null | null | null |
tcpdump
|
aa5c6b710dfd8020d2c908d6b3bd41f1da719b3b
| 1 |
ldp_tlv_print(netdissect_options *ndo,
register const u_char *tptr,
u_short msg_tlen)
{
struct ldp_tlv_header {
uint8_t type[2];
uint8_t length[2];
};
const struct ldp_tlv_header *ldp_tlv_header;
u_short tlv_type,tlv_len,tlv_tlen,af,ft_flags;
u_char fec_type;
u_int ui,vc_info_len, vc_info_tlv_type, vc_info_tlv_len,idx;
char buf[100];
int i;
ldp_tlv_header = (const struct ldp_tlv_header *)tptr;
ND_TCHECK(*ldp_tlv_header);
tlv_len=EXTRACT_16BITS(ldp_tlv_header->length);
if (tlv_len + 4 > msg_tlen) {
ND_PRINT((ndo, "\n\t\t TLV contents go past end of message"));
return 0;
}
tlv_tlen=tlv_len;
tlv_type=LDP_MASK_TLV_TYPE(EXTRACT_16BITS(ldp_tlv_header->type));
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s TLV (0x%04x), length: %u, Flags: [%s and %s forward if unknown]",
tok2str(ldp_tlv_values,
"Unknown",
tlv_type),
tlv_type,
tlv_len,
LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_tlv_header->type)) ? "continue processing" : "ignore",
LDP_MASK_F_BIT(EXTRACT_16BITS(&ldp_tlv_header->type)) ? "do" : "don't"));
tptr+=sizeof(struct ldp_tlv_header);
switch(tlv_type) {
case LDP_TLV_COMMON_HELLO:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t Hold Time: %us, Flags: [%s Hello%s]",
EXTRACT_16BITS(tptr),
(EXTRACT_16BITS(tptr+2)&0x8000) ? "Targeted" : "Link",
(EXTRACT_16BITS(tptr+2)&0x4000) ? ", Request for targeted Hellos" : ""));
break;
case LDP_TLV_IPV4_TRANSPORT_ADDR:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t IPv4 Transport Address: %s", ipaddr_string(ndo, tptr)));
break;
case LDP_TLV_IPV6_TRANSPORT_ADDR:
TLV_TCHECK(16);
ND_PRINT((ndo, "\n\t IPv6 Transport Address: %s", ip6addr_string(ndo, tptr)));
break;
case LDP_TLV_CONFIG_SEQ_NUMBER:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t Sequence Number: %u", EXTRACT_32BITS(tptr)));
break;
case LDP_TLV_ADDRESS_LIST:
TLV_TCHECK(LDP_TLV_ADDRESS_LIST_AFNUM_LEN);
af = EXTRACT_16BITS(tptr);
tptr+=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
tlv_tlen -= LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
ND_PRINT((ndo, "\n\t Address Family: %s, addresses",
tok2str(af_values, "Unknown (%u)", af)));
switch (af) {
case AFNUM_INET:
while(tlv_tlen >= sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, " %s", ipaddr_string(ndo, tptr)));
tlv_tlen-=sizeof(struct in_addr);
tptr+=sizeof(struct in_addr);
}
break;
case AFNUM_INET6:
while(tlv_tlen >= sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, " %s", ip6addr_string(ndo, tptr)));
tlv_tlen-=sizeof(struct in6_addr);
tptr+=sizeof(struct in6_addr);
}
break;
default:
/* unknown AF */
break;
}
break;
case LDP_TLV_COMMON_SESSION:
TLV_TCHECK(8);
ND_PRINT((ndo, "\n\t Version: %u, Keepalive: %us, Flags: [Downstream %s, Loop Detection %s]",
EXTRACT_16BITS(tptr), EXTRACT_16BITS(tptr+2),
(EXTRACT_16BITS(tptr+6)&0x8000) ? "On Demand" : "Unsolicited",
(EXTRACT_16BITS(tptr+6)&0x4000) ? "Enabled" : "Disabled"
));
break;
case LDP_TLV_FEC:
TLV_TCHECK(1);
fec_type = *tptr;
ND_PRINT((ndo, "\n\t %s FEC (0x%02x)",
tok2str(ldp_fec_values, "Unknown", fec_type),
fec_type));
tptr+=1;
tlv_tlen-=1;
switch(fec_type) {
case LDP_FEC_WILDCARD:
break;
case LDP_FEC_PREFIX:
TLV_TCHECK(2);
af = EXTRACT_16BITS(tptr);
tptr+=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
tlv_tlen-=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
if (af == AFNUM_INET) {
i=decode_prefix4(ndo, tptr, tlv_tlen, buf, sizeof(buf));
if (i == -2)
goto trunc;
if (i == -3)
ND_PRINT((ndo, ": IPv4 prefix (goes past end of TLV)"));
else if (i == -1)
ND_PRINT((ndo, ": IPv4 prefix (invalid length)"));
else
ND_PRINT((ndo, ": IPv4 prefix %s", buf));
}
else if (af == AFNUM_INET6) {
i=decode_prefix6(ndo, tptr, tlv_tlen, buf, sizeof(buf));
if (i == -2)
goto trunc;
if (i == -3)
ND_PRINT((ndo, ": IPv4 prefix (goes past end of TLV)"));
else if (i == -1)
ND_PRINT((ndo, ": IPv6 prefix (invalid length)"));
else
ND_PRINT((ndo, ": IPv6 prefix %s", buf));
}
else
ND_PRINT((ndo, ": Address family %u prefix", af));
break;
case LDP_FEC_HOSTADDRESS:
break;
case LDP_FEC_MARTINI_VC:
/*
* We assume the type was supposed to be one of the MPLS
* Pseudowire Types.
*/
TLV_TCHECK(7);
vc_info_len = *(tptr+2);
/*
* According to RFC 4908, the VC info Length field can be zero,
* in which case not only are there no interface parameters,
* there's no VC ID.
*/
if (vc_info_len == 0) {
ND_PRINT((ndo, ": %s, %scontrol word, group-ID %u, VC-info-length: %u",
tok2str(mpls_pw_types_values, "Unknown", EXTRACT_16BITS(tptr)&0x7fff),
EXTRACT_16BITS(tptr)&0x8000 ? "" : "no ",
EXTRACT_32BITS(tptr+3),
vc_info_len));
break;
}
/* Make sure we have the VC ID as well */
TLV_TCHECK(11);
ND_PRINT((ndo, ": %s, %scontrol word, group-ID %u, VC-ID %u, VC-info-length: %u",
tok2str(mpls_pw_types_values, "Unknown", EXTRACT_16BITS(tptr)&0x7fff),
EXTRACT_16BITS(tptr)&0x8000 ? "" : "no ",
EXTRACT_32BITS(tptr+3),
EXTRACT_32BITS(tptr+7),
vc_info_len));
if (vc_info_len < 4) {
/* minimum 4, for the VC ID */
ND_PRINT((ndo, " (invalid, < 4"));
return(tlv_len+4); /* Type & Length fields not included */
}
vc_info_len -= 4; /* subtract out the VC ID, giving the length of the interface parameters */
/* Skip past the fixed information and the VC ID */
tptr+=11;
tlv_tlen-=11;
TLV_TCHECK(vc_info_len);
while (vc_info_len > 2) {
vc_info_tlv_type = *tptr;
vc_info_tlv_len = *(tptr+1);
if (vc_info_tlv_len < 2)
break;
if (vc_info_len < vc_info_tlv_len)
break;
ND_PRINT((ndo, "\n\t\tInterface Parameter: %s (0x%02x), len %u",
tok2str(ldp_fec_martini_ifparm_values,"Unknown",vc_info_tlv_type),
vc_info_tlv_type,
vc_info_tlv_len));
switch(vc_info_tlv_type) {
case LDP_FEC_MARTINI_IFPARM_MTU:
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(tptr+2)));
break;
case LDP_FEC_MARTINI_IFPARM_DESC:
ND_PRINT((ndo, ": "));
for (idx = 2; idx < vc_info_tlv_len; idx++)
safeputchar(ndo, *(tptr + idx));
break;
case LDP_FEC_MARTINI_IFPARM_VCCV:
ND_PRINT((ndo, "\n\t\t Control Channels (0x%02x) = [%s]",
*(tptr+2),
bittok2str(ldp_fec_martini_ifparm_vccv_cc_values, "none", *(tptr+2))));
ND_PRINT((ndo, "\n\t\t CV Types (0x%02x) = [%s]",
*(tptr+3),
bittok2str(ldp_fec_martini_ifparm_vccv_cv_values, "none", *(tptr+3))));
break;
default:
print_unknown_data(ndo, tptr+2, "\n\t\t ", vc_info_tlv_len-2);
break;
}
vc_info_len -= vc_info_tlv_len;
tptr += vc_info_tlv_len;
}
break;
}
break;
case LDP_TLV_GENERIC_LABEL:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t Label: %u", EXTRACT_32BITS(tptr) & 0xfffff));
break;
case LDP_TLV_STATUS:
TLV_TCHECK(8);
ui = EXTRACT_32BITS(tptr);
tptr+=4;
ND_PRINT((ndo, "\n\t Status: 0x%02x, Flags: [%s and %s forward]",
ui&0x3fffffff,
ui&0x80000000 ? "Fatal error" : "Advisory Notification",
ui&0x40000000 ? "do" : "don't"));
ui = EXTRACT_32BITS(tptr);
tptr+=4;
if (ui)
ND_PRINT((ndo, ", causing Message ID: 0x%08x", ui));
break;
case LDP_TLV_FT_SESSION:
TLV_TCHECK(8);
ft_flags = EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t Flags: [%sReconnect, %sSave State, %sAll-Label Protection, %s Checkpoint, %sRe-Learn State]",
ft_flags&0x8000 ? "" : "No ",
ft_flags&0x8 ? "" : "Don't ",
ft_flags&0x4 ? "" : "No ",
ft_flags&0x2 ? "Sequence Numbered Label" : "All Labels",
ft_flags&0x1 ? "" : "Don't "));
tptr+=4;
ui = EXTRACT_32BITS(tptr);
if (ui)
ND_PRINT((ndo, ", Reconnect Timeout: %ums", ui));
tptr+=4;
ui = EXTRACT_32BITS(tptr);
if (ui)
ND_PRINT((ndo, ", Recovery Time: %ums", ui));
break;
case LDP_TLV_MTU:
TLV_TCHECK(2);
ND_PRINT((ndo, "\n\t MTU: %u", EXTRACT_16BITS(tptr)));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case LDP_TLV_HOP_COUNT:
case LDP_TLV_PATH_VECTOR:
case LDP_TLV_ATM_LABEL:
case LDP_TLV_FR_LABEL:
case LDP_TLV_EXTD_STATUS:
case LDP_TLV_RETURNED_PDU:
case LDP_TLV_RETURNED_MSG:
case LDP_TLV_ATM_SESSION_PARM:
case LDP_TLV_FR_SESSION_PARM:
case LDP_TLV_LABEL_REQUEST_MSG_ID:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlv_tlen);
break;
}
return(tlv_len+4); /* Type & Length fields not included */
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
return 0;
badtlv:
ND_PRINT((ndo, "\n\t\t TLV contents go past end of TLV"));
return(tlv_len+4); /* Type & Length fields not included */
}
|
CWE-125
| 183,025 | 4,198 |
175449531126840109996265352533617078377
| null | null | null |
linux
|
0ad646c81b2182f7fa67ec0c8c825e0ee165696d
| 1 |
static int dev_get_valid_name(struct net *net,
struct net_device *dev,
const char *name)
{
BUG_ON(!net);
if (!dev_valid_name(name))
return -EINVAL;
if (strchr(name, '%'))
return dev_alloc_name_ns(net, dev, name);
else if (__dev_get_by_name(net, name))
return -EEXIST;
else if (dev->name != name)
strlcpy(dev->name, name, IFNAMSIZ);
return 0;
}
|
CWE-476
| 183,027 | 4,200 |
194124048216443325247502256018053089726
| null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.