target
int64 | func
string | cwe_id_cleaned
string | label
int64 |
|---|---|---|---|
1
|
static void gic_dist_writel(void *opaque, hwaddr offset,
uint32_t value, MemTxAttrs attrs)
{
GICState *s = (GICState *)opaque;
if (offset == 0xf00) {
int cpu;
int irq;
int mask;
int target_cpu;
cpu = gic_get_current_cpu(s);
irq = value & 0x3ff;
switch ((value >> 24) & 3) {
case 0:
mask = (value >> 16) & ALL_CPU_MASK;
break;
case 1:
mask = ALL_CPU_MASK ^ (1 << cpu);
break;
case 2:
mask = 1 << cpu;
break;
default:
DPRINTF("Bad Soft Int target filter\n");
mask = ALL_CPU_MASK;
break;
}
GIC_DIST_SET_PENDING(irq, mask);
target_cpu = ctz32(mask);
while (target_cpu < GIC_NCPU) {
s->sgi_pending[irq][target_cpu] |= (1 << cpu);
mask &= ~(1 << target_cpu);
target_cpu = ctz32(mask);
}
gic_update(s);
return;
}
gic_dist_writew(opaque, offset, value & 0xffff, attrs);
gic_dist_writew(opaque, offset + 2, value >> 16, attrs);
}
|
CWE-787
| 7
|
1
|
private int
mget(struct magic_set *ms, const unsigned char *s, struct magic *m,
size_t nbytes, size_t o, unsigned int cont_level, int mode, int text,
int flip, int recursion_level, int *printed_something,
int *need_separator, int *returnval)
{
uint32_t soffset, offset = ms->offset;
uint32_t count = m->str_range;
int rv, oneed_separator;
char *sbuf, *rbuf;
union VALUETYPE *p = &ms->ms_value;
struct mlist ml;
if (recursion_level >= 20) {
file_error(ms, 0, "recursion nesting exceeded");
return -1;
}
if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),
(uint32_t)nbytes, count) == -1)
return -1;
if ((ms->flags & MAGIC_DEBUG) != 0) {
fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, "
"nbytes=%zu, count=%u)\n", m->type, m->flag, offset, o,
nbytes, count);
mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));
}
if (m->flag & INDIR) {
int off = m->in_offset;
if (m->in_op & FILE_OPINDIRECT) {
const union VALUETYPE *q = CAST(const union VALUETYPE *,
((const void *)(s + offset + off)));
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
off = q->b;
break;
case FILE_SHORT:
off = q->h;
break;
case FILE_BESHORT:
off = (short)((q->hs[0]<<8)|(q->hs[1]));
break;
case FILE_LESHORT:
off = (short)((q->hs[1]<<8)|(q->hs[0]));
break;
case FILE_LONG:
off = q->l;
break;
case FILE_BELONG:
case FILE_BEID3:
off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)|
(q->hl[2]<<8)|(q->hl[3]));
break;
case FILE_LEID3:
case FILE_LELONG:
off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)|
(q->hl[1]<<8)|(q->hl[0]));
break;
case FILE_MELONG:
off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)|
(q->hl[3]<<8)|(q->hl[2]));
break;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect offs=%u\n", off);
}
switch (cvt_flip(m->in_type, flip)) {
case FILE_BYTE:
if (nbytes < (offset + 1))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->b & off;
break;
case FILE_OPOR:
offset = p->b | off;
break;
case FILE_OPXOR:
offset = p->b ^ off;
break;
case FILE_OPADD:
offset = p->b + off;
break;
case FILE_OPMINUS:
offset = p->b - off;
break;
case FILE_OPMULTIPLY:
offset = p->b * off;
break;
case FILE_OPDIVIDE:
offset = p->b / off;
break;
case FILE_OPMODULO:
offset = p->b % off;
break;
}
} else
offset = p->b;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BESHORT:
if (nbytes < (offset + 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) &
off;
break;
case FILE_OPOR:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) |
off;
break;
case FILE_OPXOR:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) ^
off;
break;
case FILE_OPADD:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) +
off;
break;
case FILE_OPMINUS:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) *
off;
break;
case FILE_OPDIVIDE:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) /
off;
break;
case FILE_OPMODULO:
offset = (short)((p->hs[0]<<8)|
(p->hs[1])) %
off;
break;
}
} else
offset = (short)((p->hs[0]<<8)|
(p->hs[1]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LESHORT:
if (nbytes < (offset + 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) &
off;
break;
case FILE_OPOR:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) |
off;
break;
case FILE_OPXOR:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) ^
off;
break;
case FILE_OPADD:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) +
off;
break;
case FILE_OPMINUS:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) *
off;
break;
case FILE_OPDIVIDE:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) /
off;
break;
case FILE_OPMODULO:
offset = (short)((p->hs[1]<<8)|
(p->hs[0])) %
off;
break;
}
} else
offset = (short)((p->hs[1]<<8)|
(p->hs[0]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_SHORT:
if (nbytes < (offset + 2))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->h & off;
break;
case FILE_OPOR:
offset = p->h | off;
break;
case FILE_OPXOR:
offset = p->h ^ off;
break;
case FILE_OPADD:
offset = p->h + off;
break;
case FILE_OPMINUS:
offset = p->h - off;
break;
case FILE_OPMULTIPLY:
offset = p->h * off;
break;
case FILE_OPDIVIDE:
offset = p->h / off;
break;
case FILE_OPMODULO:
offset = p->h % off;
break;
}
}
else
offset = p->h;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_BELONG:
case FILE_BEID3:
if (nbytes < (offset + 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[0]<<24)|
(p->hl[1]<<16)|
(p->hl[2]<<8)|
(p->hl[3]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LELONG:
case FILE_LEID3:
if (nbytes < (offset + 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[3]<<24)|
(p->hl[2]<<16)|
(p->hl[1]<<8)|
(p->hl[0]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_MELONG:
if (nbytes < (offset + 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) &
off;
break;
case FILE_OPOR:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) |
off;
break;
case FILE_OPXOR:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) ^
off;
break;
case FILE_OPADD:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) +
off;
break;
case FILE_OPMINUS:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) -
off;
break;
case FILE_OPMULTIPLY:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) *
off;
break;
case FILE_OPDIVIDE:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) /
off;
break;
case FILE_OPMODULO:
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2])) %
off;
break;
}
} else
offset = (int32_t)((p->hl[1]<<24)|
(p->hl[0]<<16)|
(p->hl[3]<<8)|
(p->hl[2]));
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
case FILE_LONG:
if (nbytes < (offset + 4))
return 0;
if (off) {
switch (m->in_op & FILE_OPS_MASK) {
case FILE_OPAND:
offset = p->l & off;
break;
case FILE_OPOR:
offset = p->l | off;
break;
case FILE_OPXOR:
offset = p->l ^ off;
break;
case FILE_OPADD:
offset = p->l + off;
break;
case FILE_OPMINUS:
offset = p->l - off;
break;
case FILE_OPMULTIPLY:
offset = p->l * off;
break;
case FILE_OPDIVIDE:
offset = p->l / off;
break;
case FILE_OPMODULO:
offset = p->l % off;
break;
}
} else
offset = p->l;
if (m->in_op & FILE_OPINVERSE)
offset = ~offset;
break;
}
switch (cvt_flip(m->in_type, flip)) {
case FILE_LEID3:
case FILE_BEID3:
offset = ((((offset >> 0) & 0x7f) << 0) |
(((offset >> 8) & 0x7f) << 7) |
(((offset >> 16) & 0x7f) << 14) |
(((offset >> 24) & 0x7f) << 21)) + 10;
break;
default:
break;
}
if (m->flag & INDIROFFADD) {
offset += ms->c.li[cont_level-1].off;
if (offset == 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr,
"indirect *zero* offset\n");
return 0;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect +offs=%u\n", offset);
}
if (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)
return -1;
ms->offset = offset;
if ((ms->flags & MAGIC_DEBUG) != 0) {
mdebug(offset, (char *)(void *)p,
sizeof(union VALUETYPE));
}
}
/* Verify we have enough data to match magic type */
switch (m->type) {
case FILE_BYTE:
if (nbytes < (offset + 1)) /* should always be true */
return 0;
break;
case FILE_SHORT:
case FILE_BESHORT:
case FILE_LESHORT:
if (nbytes < (offset + 2))
return 0;
break;
case FILE_LONG:
case FILE_BELONG:
case FILE_LELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_BEDATE:
case FILE_LEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_BELDATE:
case FILE_LELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
if (nbytes < (offset + 4))
return 0;
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
if (nbytes < (offset + 8))
return 0;
break;
case FILE_STRING:
case FILE_PSTRING:
case FILE_SEARCH:
if (nbytes < (offset + m->vallen))
return 0;
break;
case FILE_REGEX:
if (nbytes < offset)
return 0;
break;
case FILE_INDIRECT:
if (offset == 0)
return 0;
if (nbytes < offset)
return 0;
sbuf = ms->o.buf;
soffset = ms->offset;
ms->o.buf = NULL;
ms->offset = 0;
rv = file_softmagic(ms, s + offset, nbytes - offset,
recursion_level, BINTEST, text);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv);
rbuf = ms->o.buf;
ms->o.buf = sbuf;
ms->offset = soffset;
if (rv == 1) {
if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 &&
file_printf(ms, m->desc, offset) == -1) {
if (rbuf) {
efree(rbuf);
}
return -1;
}
if (file_printf(ms, "%s", rbuf) == -1) {
if (rbuf) {
efree(rbuf);
}
return -1;
}
}
if (rbuf) {
efree(rbuf);
}
return rv;
case FILE_USE:
if (nbytes < offset)
return 0;
sbuf = m->value.s;
if (*sbuf == '^') {
sbuf++;
flip = !flip;
}
if (file_magicfind(ms, sbuf, &ml) == -1) {
file_error(ms, 0, "cannot find entry `%s'", sbuf);
return -1;
}
oneed_separator = *need_separator;
if (m->flag & NOSPACE)
*need_separator = 0;
rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o,
mode, text, flip, recursion_level, printed_something,
need_separator, returnval);
if (rv != 1)
*need_separator = oneed_separator;
return rv;
case FILE_NAME:
if (file_printf(ms, "%s", m->desc) == -1)
return -1;
return 1;
case FILE_DEFAULT: /* nothing to check */
default:
break;
}
if (!mconvert(ms, m, flip))
return 0;
|
CWE-119
| 0
|
0
|
poppler_page_get_link_mapping (PopplerPage *page)
{
GList *map_list = NULL;
gint i;
Links *links;
Object obj;
double width, height;
g_return_val_if_fail (POPPLER_IS_PAGE (page), NULL);
links = new Links (page->page->getAnnots (&obj),
page->document->doc->getCatalog ()->getBaseURI ());
obj.free ();
if (links == NULL)
return NULL;
poppler_page_get_size (page, &width, &height);
for (i = 0; i < links->getNumLinks (); i++)
{
PopplerLinkMapping *mapping;
PopplerRectangle rect;
LinkAction *link_action;
Link *link;
link = links->getLink (i);
link_action = link->getAction ();
/* Create the mapping */
mapping = g_new (PopplerLinkMapping, 1);
mapping->action = _poppler_action_new (page->document, link_action, NULL);
link->getRect (&rect.x1, &rect.y1, &rect.x2, &rect.y2);
switch (page->page->getRotate ())
{
case 90:
mapping->area.x1 = rect.y1;
mapping->area.y1 = height - rect.x2;
mapping->area.x2 = mapping->area.x1 + (rect.y2 - rect.y1);
mapping->area.y2 = mapping->area.y1 + (rect.x2 - rect.x1);
break;
case 180:
mapping->area.x1 = width - rect.x2;
mapping->area.y1 = height - rect.y2;
mapping->area.x2 = mapping->area.x1 + (rect.x2 - rect.x1);
mapping->area.y2 = mapping->area.y1 + (rect.y2 - rect.y1);
break;
case 270:
mapping->area.x1 = width - rect.y2;
mapping->area.y1 = rect.x1;
mapping->area.x2 = mapping->area.x1 + (rect.y2 - rect.y1);
mapping->area.y2 = mapping->area.y1 + (rect.x2 - rect.x1);
break;
default:
mapping->area.x1 = rect.x1;
mapping->area.y1 = rect.y1;
mapping->area.x2 = rect.x2;
mapping->area.y2 = rect.y2;
}
mapping->area.x1 -= page->page->getCropBox()->x1;
mapping->area.x2 -= page->page->getCropBox()->x1;
mapping->area.y1 -= page->page->getCropBox()->y1;
mapping->area.y2 -= page->page->getCropBox()->y1;
map_list = g_list_prepend (map_list, mapping);
}
delete links;
return map_list;
}
|
none
| 8
|
1
|
static void hid_input_field(struct hid_device *hid, struct hid_field *field,
__u8 *data, int interrupt)
{
unsigned n;
unsigned count = field->report_count;
unsigned offset = field->report_offset;
unsigned size = field->report_size;
__s32 min = field->logical_minimum;
__s32 max = field->logical_maximum;
__s32 *value;
value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);
if (!value)
return;
for (n = 0; n < count; n++) {
value[n] = min < 0 ?
snto32(hid_field_extract(hid, data, offset + n * size,
size), size) :
hid_field_extract(hid, data, offset + n * size, size);
/* Ignore report if ErrorRollOver */
if (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&
value[n] >= min && value[n] <= max &&
field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)
goto exit;
}
for (n = 0; n < count; n++) {
if (HID_MAIN_ITEM_VARIABLE & field->flags) {
hid_process_event(hid, field, &field->usage[n], value[n], interrupt);
continue;
}
if (field->value[n] >= min && field->value[n] <= max
&& field->usage[field->value[n] - min].hid
&& search(value, field->value[n], count))
hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);
if (value[n] >= min && value[n] <= max
&& field->usage[value[n] - min].hid
&& search(field->value, value[n], count))
hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);
}
memcpy(field->value, value, count * sizeof(__s32));
exit:
kfree(value);
}
|
CWE-125
| 1
|
1
|
static void rpza_decode_stream(RpzaContext *s)
{
int width = s->avctx->width;
int stride = s->frame.linesize[0] / 2;
int row_inc = stride - 4;
int stream_ptr = 0;
int chunk_size;
unsigned char opcode;
int n_blocks;
unsigned short colorA = 0, colorB;
unsigned short color4[4];
unsigned char index, idx;
unsigned short ta, tb;
unsigned short *pixels = (unsigned short *)s->frame.data[0];
int row_ptr = 0;
int pixel_ptr = 0;
int block_ptr;
int pixel_x, pixel_y;
int total_blocks;
/* First byte is always 0xe1. Warn if it's different */
if (s->buf[stream_ptr] != 0xe1)
av_log(s->avctx, AV_LOG_ERROR, "First chunk byte is 0x%02x instead of 0xe1\n",
s->buf[stream_ptr]);
/* Get chunk size, ingnoring first byte */
chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF;
stream_ptr += 4;
/* If length mismatch use size from MOV file and try to decode anyway */
if (chunk_size != s->size)
av_log(s->avctx, AV_LOG_ERROR, "MOV chunk size != encoded chunk size; using MOV chunk size\n");
chunk_size = s->size;
/* Number of 4x4 blocks in frame. */
total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4);
/* Process chunk data */
while (stream_ptr < chunk_size) {
opcode = s->buf[stream_ptr++]; /* Get opcode */
n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */
/* If opcode MSbit is 0, we need more data to decide what to do */
if ((opcode & 0x80) == 0) {
colorA = (opcode << 8) | (s->buf[stream_ptr++]);
opcode = 0;
if ((s->buf[stream_ptr] & 0x80) != 0) {
/* Must behave as opcode 110xxxxx, using colorA computed
* above. Use fake opcode 0x20 to enter switch block at
* the right place */
opcode = 0x20;
n_blocks = 1;
}
}
switch (opcode & 0xe0) {
/* Skip blocks */
case 0x80:
while (n_blocks--) {
ADVANCE_BLOCK();
}
break;
/* Fill blocks with one color */
case 0xa0:
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
while (n_blocks--) {
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
for (pixel_x = 0; pixel_x < 4; pixel_x++){
pixels[block_ptr] = colorA;
block_ptr++;
}
block_ptr += row_inc;
}
ADVANCE_BLOCK();
}
break;
/* Fill blocks with 4 colors */
case 0xc0:
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
case 0x20:
colorB = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
/* sort out the colors */
color4[0] = colorB;
color4[1] = 0;
color4[2] = 0;
color4[3] = colorA;
/* red components */
ta = (colorA >> 10) & 0x1F;
tb = (colorB >> 10) & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10;
color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10;
/* green components */
ta = (colorA >> 5) & 0x1F;
tb = (colorB >> 5) & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5;
color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5;
/* blue components */
ta = colorA & 0x1F;
tb = colorB & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5);
color4[2] |= ((21 * ta + 11 * tb) >> 5);
if (s->size - stream_ptr < n_blocks * 4)
return;
while (n_blocks--) {
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
index = s->buf[stream_ptr++];
for (pixel_x = 0; pixel_x < 4; pixel_x++){
idx = (index >> (2 * (3 - pixel_x))) & 0x03;
pixels[block_ptr] = color4[idx];
block_ptr++;
}
block_ptr += row_inc;
}
ADVANCE_BLOCK();
}
break;
/* Fill block with 16 colors */
case 0x00:
if (s->size - stream_ptr < 16)
return;
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
for (pixel_x = 0; pixel_x < 4; pixel_x++){
/* We already have color of upper left pixel */
if ((pixel_y != 0) || (pixel_x !=0)) {
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
}
pixels[block_ptr] = colorA;
block_ptr++;
}
block_ptr += row_inc;
}
ADVANCE_BLOCK();
break;
/* Unknown opcode */
default:
av_log(s->avctx, AV_LOG_ERROR, "Unknown opcode %d in rpza chunk."
" Skip remaining %d bytes of chunk data.\n", opcode,
chunk_size - stream_ptr);
return;
} /* Opcode switch */
}
}
|
CWE-119
| 0
|
1
|
int get_devices_from_authfile(const char *authfile, const char *username,
unsigned max_devs, int verbose, FILE *debug_file,
device_t *devices, unsigned *n_devs) {
char *buf = NULL;
char *s_user, *s_token;
int retval = 0;
int fd = -1;
struct stat st;
struct passwd *pw = NULL, pw_s;
char buffer[BUFSIZE];
int gpu_ret;
FILE *opwfile = NULL;
unsigned i, j;
/* Ensure we never return uninitialized count. */
*n_devs = 0;
fd = open(authfile, O_RDONLY | O_CLOEXEC | O_NOCTTY);
if (fd < 0) {
if (verbose)
D(debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno));
goto err;
}
if (fstat(fd, &st) < 0) {
if (verbose)
D(debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno));
goto err;
}
if (!S_ISREG(st.st_mode)) {
if (verbose)
D(debug_file, "%s is not a regular file", authfile);
goto err;
}
if (st.st_size == 0) {
if (verbose)
D(debug_file, "File %s is empty", authfile);
goto err;
}
gpu_ret = getpwuid_r(st.st_uid, &pw_s, buffer, sizeof(buffer), &pw);
if (gpu_ret != 0 || pw == NULL) {
D(debug_file, "Unable to retrieve credentials for uid %u, (%s)", st.st_uid,
strerror(errno));
goto err;
}
if (strcmp(pw->pw_name, username) != 0 && strcmp(pw->pw_name, "root") != 0) {
if (strcmp(username, "root") != 0) {
D(debug_file, "The owner of the authentication file is neither %s nor root",
username);
} else {
D(debug_file, "The owner of the authentication file is not root");
}
goto err;
}
opwfile = fdopen(fd, "r");
if (opwfile == NULL) {
if (verbose)
D(debug_file, "fdopen: %s", strerror(errno));
goto err;
} else {
fd = -1; /* fd belongs to opwfile */
}
buf = malloc(sizeof(char) * (DEVSIZE * max_devs));
if (!buf) {
if (verbose)
D(debug_file, "Unable to allocate memory");
goto err;
}
retval = -2;
while (fgets(buf, (int)(DEVSIZE * (max_devs - 1)), opwfile)) {
char *saveptr = NULL;
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0';
if (verbose)
D(debug_file, "Authorization line: %s", buf);
s_user = strtok_r(buf, ":", &saveptr);
if (s_user && strcmp(username, s_user) == 0) {
if (verbose)
D(debug_file, "Matched user: %s", s_user);
retval = -1; // We found at least one line for the user
// only keep last line for this user
for (i = 0; i < *n_devs; i++) {
free(devices[i].keyHandle);
free(devices[i].publicKey);
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
}
*n_devs = 0;
i = 0;
while ((s_token = strtok_r(NULL, ",", &saveptr))) {
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
if ((*n_devs)++ > MAX_DEVS - 1) {
*n_devs = MAX_DEVS;
if (verbose)
D(debug_file, "Found more than %d devices, ignoring the remaining ones",
MAX_DEVS);
break;
}
if (verbose)
D(debug_file, "KeyHandle for device number %d: %s", i + 1, s_token);
devices[i].keyHandle = strdup(s_token);
if (!devices[i].keyHandle) {
if (verbose)
D(debug_file, "Unable to allocate memory for keyHandle number %d", i);
goto err;
}
s_token = strtok_r(NULL, ":", &saveptr);
if (!s_token) {
if (verbose)
D(debug_file, "Unable to retrieve publicKey number %d", i + 1);
goto err;
}
if (verbose)
D(debug_file, "publicKey for device number %d: %s", i + 1, s_token);
if (strlen(s_token) % 2 != 0) {
if (verbose)
D(debug_file, "Length of key number %d not even", i + 1);
goto err;
}
devices[i].key_len = strlen(s_token) / 2;
if (verbose)
D(debug_file, "Length of key number %d is %zu", i + 1, devices[i].key_len);
devices[i].publicKey =
malloc((sizeof(unsigned char) * devices[i].key_len));
if (!devices[i].publicKey) {
if (verbose)
D(debug_file, "Unable to allocate memory for publicKey number %d", i);
goto err;
}
for (j = 0; j < devices[i].key_len; j++) {
unsigned int x;
if (sscanf(&s_token[2 * j], "%2x", &x) != 1) {
if (verbose)
D(debug_file, "Invalid hex number in key");
goto err;
}
devices[i].publicKey[j] = (unsigned char)x;
}
i++;
}
}
}
if (verbose)
D(debug_file, "Found %d device(s) for user %s", *n_devs, username);
retval = 1;
goto out;
err:
for (i = 0; i < *n_devs; i++) {
free(devices[i].keyHandle);
free(devices[i].publicKey);
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
}
*n_devs = 0;
out:
if (buf) {
free(buf);
buf = NULL;
}
if (opwfile)
fclose(opwfile);
if (fd != -1)
close(fd);
return retval;
}
|
CWE-787
| 7
|
1
|
SplashPath *Splash::makeDashedPath(SplashPath *path) {
SplashPath *dPath;
SplashCoord lineDashTotal;
SplashCoord lineDashStartPhase, lineDashDist, segLen;
SplashCoord x0, y0, x1, y1, xa, ya;
GBool lineDashStartOn, lineDashOn, newPath;
int lineDashStartIdx, lineDashIdx;
int i, j, k;
lineDashTotal = 0;
for (i = 0; i < state->lineDashLength; ++i) {
lineDashTotal += state->lineDash[i];
}
// Acrobat simply draws nothing if the dash array is [0]
if (lineDashTotal == 0) {
return new SplashPath();
}
lineDashStartPhase = state->lineDashPhase;
i = splashFloor(lineDashStartPhase / lineDashTotal);
lineDashStartPhase -= (SplashCoord)i * lineDashTotal;
lineDashStartOn = gTrue;
lineDashStartIdx = 0;
if (lineDashStartPhase > 0) {
while (lineDashStartPhase >= state->lineDash[lineDashStartIdx]) {
lineDashStartOn = !lineDashStartOn;
lineDashStartPhase -= state->lineDash[lineDashStartIdx];
++lineDashStartIdx;
}
}
dPath = new SplashPath();
// process each subpath
i = 0;
while (i < path->length) {
// find the end of the subpath
for (j = i;
j < path->length - 1 && !(path->flags[j] & splashPathLast);
++j) ;
// initialize the dash parameters
lineDashOn = lineDashStartOn;
lineDashIdx = lineDashStartIdx;
lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase;
// process each segment of the subpath
newPath = gTrue;
for (k = i; k < j; ++k) {
// grab the segment
x0 = path->pts[k].x;
y0 = path->pts[k].y;
x1 = path->pts[k+1].x;
y1 = path->pts[k+1].y;
segLen = splashDist(x0, y0, x1, y1);
// process the segment
while (segLen > 0) {
if (lineDashDist >= segLen) {
if (lineDashOn) {
if (newPath) {
dPath->moveTo(x0, y0);
newPath = gFalse;
}
dPath->lineTo(x1, y1);
}
lineDashDist -= segLen;
segLen = 0;
} else {
xa = x0 + (lineDashDist / segLen) * (x1 - x0);
ya = y0 + (lineDashDist / segLen) * (y1 - y0);
if (lineDashOn) {
if (newPath) {
dPath->moveTo(x0, y0);
newPath = gFalse;
}
dPath->lineTo(xa, ya);
}
x0 = xa;
y0 = ya;
segLen -= lineDashDist;
lineDashDist = 0;
}
// get the next entry in the dash array
if (lineDashDist <= 0) {
lineDashOn = !lineDashOn;
if (++lineDashIdx == state->lineDashLength) {
lineDashIdx = 0;
}
lineDashDist = state->lineDash[lineDashIdx];
newPath = gTrue;
}
}
}
i = j + 1;
}
if (dPath->length == 0) {
GBool allSame = gTrue;
for (int i = 0; allSame && i < path->length - 1; ++i) {
allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y;
}
if (allSame) {
x0 = path->pts[0].x;
y0 = path->pts[0].y;
dPath->moveTo(x0, y0);
dPath->lineTo(x0, y0);
}
}
return dPath;
}
|
CWE-119
| 0
|
1
|
Strgrow(Str x)
{
char *old = x->ptr;
int newlen;
newlen = x->length * 6 / 5;
if (newlen == x->length)
newlen += 2;
x->ptr = GC_MALLOC_ATOMIC(newlen);
x->area_size = newlen;
bcopy((void *)old, (void *)x->ptr, x->length);
GC_free(old);
}
|
CWE-119
| 0
|
1
|
void Compute(OpKernelContext* context) override {
const Tensor& contents = context->input(0);
OP_REQUIRES(context, TensorShapeUtils::IsScalar(contents.shape()),
errors::InvalidArgument("contents must be scalar, got shape ",
contents.shape().DebugString()));
// Start decoding image to get shape details
const StringPiece input = contents.scalar<string>()();
OP_REQUIRES(context, (32 <= input.size()),
errors::InvalidArgument("Incomplete bmp content, requires at "
"least 32 bytes to find the header "
"size, width, height, and bpp, got ",
input.size(), " bytes"));
const uint8* img_bytes = reinterpret_cast<const uint8*>(input.data());
int32 header_size_ = internal::SubtleMustCopy(
*(reinterpret_cast<const int32*>(img_bytes + 10)));
const int32 header_size = ByteSwapInt32ForBigEndian(header_size_);
int32 width_ = internal::SubtleMustCopy(
*(reinterpret_cast<const int32*>(img_bytes + 18)));
const int32 width = ByteSwapInt32ForBigEndian(width_);
int32 height_ = internal::SubtleMustCopy(
*(reinterpret_cast<const int32*>(img_bytes + 22)));
const int32 height = ByteSwapInt32ForBigEndian(height_);
int32 bpp_ = internal::SubtleMustCopy(
*(reinterpret_cast<const int32*>(img_bytes + 28)));
const int32 bpp = ByteSwapInt32ForBigEndian(bpp_);
if (channels_) {
OP_REQUIRES(context, (channels_ == bpp / 8),
errors::InvalidArgument(
"channels attribute ", channels_,
" does not match bits per pixel from file ", bpp / 8));
} else {
channels_ = bpp / 8;
}
// Current implementation only supports 1, 3 or 4 channel
// bitmaps.
OP_REQUIRES(context, (channels_ == 1 || channels_ == 3 || channels_ == 4),
errors::InvalidArgument(
"Number of channels must be 1, 3 or 4, was ", channels_));
// there may be padding bytes when the width is not a multiple of 4 bytes
// 8 * channels == bits per pixel
const int row_size = (8 * channels_ * width + 31) / 32 * 4;
const int last_pixel_offset =
header_size + (abs(height) - 1) * row_size + (width - 1) * channels_;
// [expected file size] = [last pixel offset] + [last pixel size=channels]
const int expected_file_size = last_pixel_offset + channels_;
OP_REQUIRES(
context, (expected_file_size <= input.size()),
errors::InvalidArgument("Incomplete bmp content, requires at least ",
expected_file_size, " bytes, got ",
input.size(), " bytes"));
// if height is negative, data layout is top down
// otherwise, it's bottom up
bool top_down = (height < 0);
// Decode image, allocating tensor once the image size is known
Tensor* output = nullptr;
OP_REQUIRES_OK(
context, context->allocate_output(
0, TensorShape({abs(height), width, channels_}), &output));
const uint8* bmp_pixels = &img_bytes[header_size];
Decode(bmp_pixels, row_size, output->flat<uint8>().data(), width,
abs(height), channels_, top_down);
}
|
CWE-20
| 2
|
0
|
GfxColorSpace *GfxSeparationColorSpace::copy() {
return new GfxSeparationColorSpace(name->copy(), alt->copy(), func->copy());
}
|
none
| 8
|
0
|
int reds_expects_link_id(uint32_t connection_id)
{
spice_info("TODO: keep a list of connection_id's from migration, compare to them");
return 1;
}
|
none
| 8
|
0
|
poppler_page_get_image_mapping (PopplerPage *page)
{
return NULL;
}
|
none
| 8
|
0
|
int ssl3_put_cipher_by_char(const SSL_CIPHER *c, unsigned char *p)
{
long l;
if (p != NULL)
{
l=c->id;
if ((l & 0xff000000) != 0x03000000) return(0);
p[0]=((unsigned char)(l>> 8L))&0xFF;
p[1]=((unsigned char)(l ))&0xFF;
}
return(2);
}
|
none
| 8
|
0
|
static int decode_filename(struct xdr_stream *xdr, char *name, u32 *length)
{
__be32 *p;
u32 count;
p = xdr_inline_decode(xdr, 4);
if (!p)
goto out_overflow;
count = ntoh32(net_read_uint32(p));
if (count > 255)
goto out_nametoolong;
p = xdr_inline_decode(xdr, count);
if (!p)
goto out_overflow;
memcpy(name, p, count);
name[count] = 0;
*length = count;
return 0;
out_nametoolong:
pr_err("%s: returned a too long filename: %u\n", __func__, count);
return -ENAMETOOLONG;
out_overflow:
pr_err("%s: premature end of packet\n", __func__);
return -EIO;
}
|
none
| 8
|
1
|
CImg<T>& _load_bmp(std::FILE *const file, const char *const filename) {
if (!file && !filename)
throw CImgArgumentException(_cimg_instance
"load_bmp(): Specified filename is (null).",
cimg_instance);
std::FILE *const nfile = file?file:cimg::fopen(filename,"rb");
CImg<ucharT> header(54);
cimg::fread(header._data,54,nfile);
if (*header!='B' || header[1]!='M') {
if (!file) cimg::fclose(nfile);
throw CImgIOException(_cimg_instance
"load_bmp(): Invalid BMP file '%s'.",
cimg_instance,
filename?filename:"(FILE*)");
}
// Read header and pixel buffer
int
file_size = header[0x02] + (header[0x03]<<8) + (header[0x04]<<16) + (header[0x05]<<24),
offset = header[0x0A] + (header[0x0B]<<8) + (header[0x0C]<<16) + (header[0x0D]<<24),
header_size = header[0x0E] + (header[0x0F]<<8) + (header[0x10]<<16) + (header[0x11]<<24),
dx = header[0x12] + (header[0x13]<<8) + (header[0x14]<<16) + (header[0x15]<<24),
dy = header[0x16] + (header[0x17]<<8) + (header[0x18]<<16) + (header[0x19]<<24),
compression = header[0x1E] + (header[0x1F]<<8) + (header[0x20]<<16) + (header[0x21]<<24),
nb_colors = header[0x2E] + (header[0x2F]<<8) + (header[0x30]<<16) + (header[0x31]<<24),
bpp = header[0x1C] + (header[0x1D]<<8);
if (!file_size || file_size==offset) {
cimg::fseek(nfile,0,SEEK_END);
file_size = (int)cimg::ftell(nfile);
cimg::fseek(nfile,54,SEEK_SET);
}
if (header_size>40) cimg::fseek(nfile,header_size - 40,SEEK_CUR);
const int
dx_bytes = (bpp==1)?(dx/8 + (dx%8?1:0)):((bpp==4)?(dx/2 + (dx%2)):(int)((longT)dx*bpp/8)),
align_bytes = (4 - dx_bytes%4)%4;
const ulongT
cimg_iobuffer = (ulongT)24*1024*1024,
buf_size = std::min((ulongT)cimg::abs(dy)*(dx_bytes + align_bytes),(ulongT)file_size - offset);
CImg<intT> colormap;
if (bpp<16) { if (!nb_colors) nb_colors = 1<<bpp; } else nb_colors = 0;
if (nb_colors) { colormap.assign(nb_colors); cimg::fread(colormap._data,nb_colors,nfile); }
const int xoffset = offset - 14 - header_size - 4*nb_colors;
if (xoffset>0) cimg::fseek(nfile,xoffset,SEEK_CUR);
CImg<ucharT> buffer;
if (buf_size<cimg_iobuffer) {
buffer.assign(cimg::abs(dy)*(dx_bytes + align_bytes),1,1,1,0);
cimg::fread(buffer._data,buf_size,nfile);
} else buffer.assign(dx_bytes + align_bytes);
unsigned char *ptrs = buffer;
// Decompress buffer (if necessary)
if (compression) {
if (file)
throw CImgIOException(_cimg_instance
"load_bmp(): Unable to load compressed data from '(*FILE)' inputs.",
cimg_instance);
else {
if (!file) cimg::fclose(nfile);
return load_other(filename);
}
}
// Read pixel data
assign(dx,cimg::abs(dy),1,3,0);
switch (bpp) {
case 1 : { // Monochrome
if (colormap._width>=2) for (int y = height() - 1; y>=0; --y) {
if (buf_size>=cimg_iobuffer) {
if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;
cimg::fseek(nfile,align_bytes,SEEK_CUR);
}
unsigned char mask = 0x80, val = 0;
cimg_forX(*this,x) {
if (mask==0x80) val = *(ptrs++);
const unsigned char *col = (unsigned char*)(colormap._data + (val&mask?1:0));
(*this)(x,y,2) = (T)*(col++);
(*this)(x,y,1) = (T)*(col++);
(*this)(x,y,0) = (T)*(col++);
mask = cimg::ror(mask);
}
ptrs+=align_bytes;
}
} break;
case 4 : { // 16 colors
if (colormap._width>=16) for (int y = height() - 1; y>=0; --y) {
if (buf_size>=cimg_iobuffer) {
if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;
cimg::fseek(nfile,align_bytes,SEEK_CUR);
}
unsigned char mask = 0xF0, val = 0;
cimg_forX(*this,x) {
if (mask==0xF0) val = *(ptrs++);
const unsigned char color = (unsigned char)((mask<16)?(val&mask):((val&mask)>>4));
const unsigned char *col = (unsigned char*)(colormap._data + color);
(*this)(x,y,2) = (T)*(col++);
(*this)(x,y,1) = (T)*(col++);
(*this)(x,y,0) = (T)*(col++);
mask = cimg::ror(mask,4);
}
ptrs+=align_bytes;
}
} break;
case 8 : { // 256 colors
if (colormap._width>=256) for (int y = height() - 1; y>=0; --y) {
if (buf_size>=cimg_iobuffer) {
if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;
cimg::fseek(nfile,align_bytes,SEEK_CUR);
}
cimg_forX(*this,x) {
const unsigned char *col = (unsigned char*)(colormap._data + *(ptrs++));
(*this)(x,y,2) = (T)*(col++);
(*this)(x,y,1) = (T)*(col++);
(*this)(x,y,0) = (T)*(col++);
}
ptrs+=align_bytes;
}
} break;
case 16 : { // 16 bits colors
for (int y = height() - 1; y>=0; --y) {
if (buf_size>=cimg_iobuffer) {
if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;
cimg::fseek(nfile,align_bytes,SEEK_CUR);
}
cimg_forX(*this,x) {
const unsigned char c1 = *(ptrs++), c2 = *(ptrs++);
const unsigned short col = (unsigned short)(c1|(c2<<8));
(*this)(x,y,2) = (T)(col&0x1F);
(*this)(x,y,1) = (T)((col>>5)&0x1F);
(*this)(x,y,0) = (T)((col>>10)&0x1F);
}
ptrs+=align_bytes;
}
} break;
case 24 : { // 24 bits colors
for (int y = height() - 1; y>=0; --y) {
if (buf_size>=cimg_iobuffer) {
if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;
cimg::fseek(nfile,align_bytes,SEEK_CUR);
}
cimg_forX(*this,x) {
(*this)(x,y,2) = (T)*(ptrs++);
(*this)(x,y,1) = (T)*(ptrs++);
(*this)(x,y,0) = (T)*(ptrs++);
}
ptrs+=align_bytes;
}
} break;
case 32 : { // 32 bits colors
for (int y = height() - 1; y>=0; --y) {
if (buf_size>=cimg_iobuffer) {
if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break;
cimg::fseek(nfile,align_bytes,SEEK_CUR);
}
cimg_forX(*this,x) {
(*this)(x,y,2) = (T)*(ptrs++);
(*this)(x,y,1) = (T)*(ptrs++);
(*this)(x,y,0) = (T)*(ptrs++);
++ptrs;
}
ptrs+=align_bytes;
}
} break;
}
if (dy<0) mirror('y');
if (!file) cimg::fclose(nfile);
return *this;
|
CWE-787
| 7
|
1
|
void Document::open(Document* entered_document,
ExceptionState& exception_state) {
if (ImportLoader()) {
exception_state.ThrowDOMException(
kInvalidStateError, "Imported document doesn't support open().");
return;
}
if (!IsHTMLDocument()) {
exception_state.ThrowDOMException(kInvalidStateError,
"Only HTML documents support open().");
return;
}
if (throw_on_dynamic_markup_insertion_count_) {
exception_state.ThrowDOMException(
kInvalidStateError,
"Custom Element constructor should not use open().");
return;
}
if (entered_document) {
if (!GetSecurityOrigin()->IsSameSchemeHostPortAndSuborigin(
entered_document->GetSecurityOrigin())) {
exception_state.ThrowSecurityError(
"Can only call open() on same-origin documents.");
return;
}
SetSecurityOrigin(entered_document->GetSecurityOrigin());
if (this != entered_document) {
KURL new_url = entered_document->Url();
new_url.SetFragmentIdentifier(String());
SetURL(new_url);
}
cookie_url_ = entered_document->CookieURL();
}
open();
}
|
CWE-20
| 2
|
1
|
void Compute(OpKernelContext* ctx) override {
StagingMap<Ordered>* map = nullptr;
OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));
core::ScopedUnref scope(map);
typename StagingMap<Ordered>::OptionalTuple tuple;
const Tensor* key_tensor;
const Tensor* indices_tensor;
OpInputList values_tensor;
OP_REQUIRES_OK(ctx, ctx->input("key", &key_tensor));
OP_REQUIRES_OK(ctx, ctx->input("indices", &indices_tensor));
OP_REQUIRES_OK(ctx, ctx->input_list("values", &values_tensor));
// Create copy for insertion into Staging Area
Tensor key(*key_tensor);
// Create the tuple to store
for (std::size_t i = 0; i < values_tensor.size(); ++i) {
tuple.push_back(values_tensor[i]);
}
// Store the tuple in the map
OP_REQUIRES_OK(ctx, map->put(&key, indices_tensor, &tuple));
}
|
CWE-476
| 6
|
0
|
static ssize_t stream_writev_cb(RedsStream *s, const struct iovec *iov, int iovcnt)
{
ssize_t ret = 0;
do {
int tosend;
ssize_t n, expected = 0;
int i;
#ifdef IOV_MAX
tosend = MIN(iovcnt, IOV_MAX);
#else
tosend = iovcnt;
#endif
for (i = 0; i < tosend; i++) {
expected += iov[i].iov_len;
}
n = writev(s->socket, iov, tosend);
if (n <= expected) {
if (n > 0)
ret += n;
return ret == 0 ? n : ret;
}
ret += n;
iov += tosend;
iovcnt -= tosend;
} while(iovcnt > 0);
return ret;
}
|
none
| 8
|
0
|
void CairoOutputDev::endPage() {
if (text) {
text->endPage();
text->coalesce(gTrue, gFalse);
}
}
|
none
| 8
|
1
|
int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error) /* {{{ */
{
phar_zip_dir_end locator;
char buf[sizeof(locator) + 65536];
zend_long size;
php_uint16 i;
phar_archive_data *mydata = NULL;
phar_entry_info entry = {0};
char *p = buf, *ext, *actual_alias = NULL;
char *metadata = NULL;
size = php_stream_tell(fp);
if (size > sizeof(locator) + 65536) {
/* seek to max comment length + end of central directory record */
size = sizeof(locator) + 65536;
if (FAILURE == php_stream_seek(fp, -size, SEEK_END)) {
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: unable to search for end of central directory in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
} else {
php_stream_seek(fp, 0, SEEK_SET);
}
if (!php_stream_read(fp, buf, size)) {
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: unable to read in data to search for end of central directory in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) {
if ((p - buf) + sizeof(locator) <= size && !memcmp(p + 1, "K\5\6", 3)) {
memcpy((void *)&locator, (void *) p, sizeof(locator));
if (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) {
/* split archives not handled */
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: split archives spanning multiple zips cannot be processed in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
if (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) {
if (error) {
spprintf(error, 4096, "phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \"%s\"", fname);
}
php_stream_close(fp);
return FAILURE;
}
mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));
mydata->is_persistent = PHAR_G(persist);
/* read in archive comment, if any */
if (PHAR_GET_16(locator.comment_len)) {
metadata = p + sizeof(locator);
if (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) {
if (error) {
spprintf(error, 4096, "phar error: corrupt zip archive, zip file comment truncated in zip-based phar \"%s\"", fname);
}
php_stream_close(fp);
pefree(mydata, mydata->is_persistent);
return FAILURE;
}
mydata->metadata_len = PHAR_GET_16(locator.comment_len);
if (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len)) == FAILURE) {
mydata->metadata_len = 0;
/* if not valid serialized data, it is a regular string */
ZVAL_NEW_STR(&mydata->metadata, zend_string_init(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent));
}
} else {
ZVAL_UNDEF(&mydata->metadata);
}
goto foundit;
}
}
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: end of central directory not found in zip-based phar \"%s\"", fname);
}
return FAILURE;
foundit:
mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent);
#ifdef PHP_WIN32
phar_unixify_path_separators(mydata->fname, fname_len);
#endif
mydata->is_zip = 1;
mydata->fname_len = fname_len;
ext = strrchr(mydata->fname, '/');
if (ext) {
mydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext);
if (mydata->ext == ext) {
mydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1);
}
if (mydata->ext) {
mydata->ext_len = (mydata->fname + fname_len) - mydata->ext;
}
}
/* clean up on big-endian systems */
/* seek to central directory */
php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);
/* read in central directory */
zend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count),
zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->mounted_dirs, 5,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
entry.phar = mydata;
entry.is_zip = 1;
entry.fp_type = PHAR_FP;
entry.is_persistent = mydata->is_persistent;
#define PHAR_ZIP_FAIL_FREE(errmsg, save) \
zend_hash_destroy(&mydata->manifest); \
mydata->manifest.u.flags = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.u.flags = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.u.flags = 0; \
php_stream_close(fp); \
zval_dtor(&mydata->metadata); \
if (mydata->signature) { \
efree(mydata->signature); \
} \
if (error) { \
spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \
} \
pefree(mydata->fname, mydata->is_persistent); \
if (mydata->alias) { \
pefree(mydata->alias, mydata->is_persistent); \
} \
pefree(mydata, mydata->is_persistent); \
efree(save); \
return FAILURE;
#define PHAR_ZIP_FAIL(errmsg) \
zend_hash_destroy(&mydata->manifest); \
mydata->manifest.u.flags = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.u.flags = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.u.flags = 0; \
php_stream_close(fp); \
zval_dtor(&mydata->metadata); \
if (mydata->signature) { \
efree(mydata->signature); \
} \
if (error) { \
spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \
} \
pefree(mydata->fname, mydata->is_persistent); \
if (mydata->alias) { \
pefree(mydata->alias, mydata->is_persistent); \
} \
pefree(mydata, mydata->is_persistent); \
return FAILURE;
/* add each central directory item to the manifest */
for (i = 0; i < PHAR_GET_16(locator.count); ++i) {
phar_zip_central_dir_file zipentry;
zend_off_t beforeus = php_stream_tell(fp);
if (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) {
PHAR_ZIP_FAIL("unable to read central directory entry, truncated");
}
/* clean up for bigendian systems */
if (memcmp("PK\1\2", zipentry.signature, 4)) {
/* corrupted entry */
PHAR_ZIP_FAIL("corrupted central directory entry, no magic signature");
}
if (entry.is_persistent) {
entry.manifest_pos = i;
}
entry.compressed_filesize = PHAR_GET_32(zipentry.compsize);
entry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize);
entry.crc32 = PHAR_GET_32(zipentry.crc32);
/* do not PHAR_GET_16 either on the next line */
entry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp);
entry.flags = PHAR_ENT_PERM_DEF_FILE;
entry.header_offset = PHAR_GET_32(zipentry.offset);
entry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) +
PHAR_GET_16(zipentry.extra_len);
if (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) {
PHAR_ZIP_FAIL("Cannot process encrypted zip files");
}
if (!PHAR_GET_16(zipentry.filename_len)) {
PHAR_ZIP_FAIL("Cannot process zips created from stdin (zero-length filename)");
}
entry.filename_len = PHAR_GET_16(zipentry.filename_len);
entry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent);
if (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in filename from central directory, truncated");
}
entry.filename[entry.filename_len] = '\0';
if (entry.filename[entry.filename_len - 1] == '/') {
entry.is_dir = 1;
if(entry.filename_len > 1) {
entry.filename_len--;
}
entry.flags |= PHAR_ENT_PERM_DEF_DIR;
} else {
entry.is_dir = 0;
}
if (entry.filename_len == sizeof(".phar/signature.bin")-1 && !strncmp(entry.filename, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) {
size_t read;
php_stream *sigfile;
zend_off_t now;
char *sig;
now = php_stream_tell(fp);
pefree(entry.filename, entry.is_persistent);
sigfile = php_stream_fopen_tmpfile();
if (!sigfile) {
PHAR_ZIP_FAIL("couldn't open temporary file");
}
php_stream_seek(fp, 0, SEEK_SET);
/* copy file contents + local headers and zip comment, if any, to be hashed for signature */
php_stream_copy_to_stream_ex(fp, sigfile, entry.header_offset, NULL);
/* seek to central directory */
php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);
/* copy central directory header */
php_stream_copy_to_stream_ex(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL);
if (metadata) {
php_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len));
}
php_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET);
sig = (char *) emalloc(entry.uncompressed_filesize);
read = php_stream_read(fp, sig, entry.uncompressed_filesize);
if (read != entry.uncompressed_filesize) {
php_stream_close(sigfile);
efree(sig);
PHAR_ZIP_FAIL("signature cannot be read");
}
mydata->sig_flags = PHAR_GET_32(sig);
if (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error)) {
efree(sig);
if (error) {
char *save;
php_stream_close(sigfile);
spprintf(&save, 4096, "signature cannot be verified: %s", *error);
efree(*error);
PHAR_ZIP_FAIL_FREE(save, save);
} else {
php_stream_close(sigfile);
PHAR_ZIP_FAIL("signature cannot be verified");
}
}
php_stream_close(sigfile);
efree(sig);
/* signature checked out, let's ensure this is the last file in the phar */
if (i != PHAR_GET_16(locator.count) - 1) {
PHAR_ZIP_FAIL("entries exist after signature, invalid phar");
}
continue;
}
phar_add_virtual_dirs(mydata, entry.filename, entry.filename_len);
if (PHAR_GET_16(zipentry.extra_len)) {
zend_off_t loc = php_stream_tell(fp);
if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("Unable to process extra field header for file in central directory");
}
php_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET);
}
switch (PHAR_GET_16(zipentry.compressed)) {
case PHAR_ZIP_COMP_NONE :
/* compression flag already set */
break;
case PHAR_ZIP_COMP_DEFLATE :
entry.flags |= PHAR_ENT_COMPRESSED_GZ;
if (!PHAR_G(has_zlib)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("zlib extension is required");
}
break;
case PHAR_ZIP_COMP_BZIP2 :
entry.flags |= PHAR_ENT_COMPRESSED_BZ2;
if (!PHAR_G(has_bz2)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("bzip2 extension is required");
}
break;
case 1 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Shrunk) used in this zip");
case 2 :
case 3 :
case 4 :
case 5 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Reduce) used in this zip");
case 6 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Implode) used in this zip");
case 7 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Tokenize) used in this zip");
case 9 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Deflate64) used in this zip");
case 10 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip");
case 14 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (LZMA) used in this zip");
case 18 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (IBM TERSE) used in this zip");
case 19 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (IBM LZ77) used in this zip");
case 97 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (WavPack) used in this zip");
case 98 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (PPMd) used in this zip");
default :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (unknown) used in this zip");
}
/* get file metadata */
if (PHAR_GET_16(zipentry.comment_len)) {
if (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in file comment, truncated");
}
p = buf;
entry.metadata_len = PHAR_GET_16(zipentry.comment_len);
if (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len)) == FAILURE) {
entry.metadata_len = 0;
/* if not valid serialized data, it is a regular string */
ZVAL_NEW_STR(&entry.metadata, zend_string_init(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent));
}
} else {
ZVAL_UNDEF(&entry.metadata);
}
if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
php_stream_filter *filter;
zend_off_t saveloc;
/* verify local file header */
phar_zip_file_header local;
/* archive alias found */
saveloc = php_stream_tell(fp);
php_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET);
if (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (cannot read local file header for alias)");
}
/* verify local header */
if (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (local header of alias does not match central directory)");
}
/* construct actual offset to file start - local extra_len can be different from central extra_len */
entry.offset = entry.offset_abs =
sizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len);
php_stream_seek(fp, entry.offset, SEEK_SET);
/* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */
fp->writepos = 0;
fp->readpos = 0;
php_stream_seek(fp, entry.offset, SEEK_SET);
fp->writepos = 0;
fp->readpos = 0;
/* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */
mydata->alias_len = entry.uncompressed_filesize;
if (entry.flags & PHAR_ENT_COMPRESSED_GZ) {
filter = php_stream_filter_create("zlib.inflate", NULL, php_stream_is_persistent(fp));
if (!filter) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to decompress alias, zlib filter creation failed");
}
php_stream_filter_append(&fp->readfilters, filter);
// TODO: refactor to avoid reallocation ???
//??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)
{
zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);
if (str) {
entry.uncompressed_filesize = ZSTR_LEN(str);
actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
actual_alias = NULL;
entry.uncompressed_filesize = 0;
}
}
if (!entry.uncompressed_filesize || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1);
} else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) {
filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp));
if (!filter) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, bzip2 filter creation failed");
}
php_stream_filter_append(&fp->readfilters, filter);
// TODO: refactor to avoid reallocation ???
//??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)
{
zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);
if (str) {
entry.uncompressed_filesize = ZSTR_LEN(str);
actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
actual_alias = NULL;
entry.uncompressed_filesize = 0;
}
}
if (!entry.uncompressed_filesize || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1);
} else {
// TODO: refactor to avoid reallocation ???
//??? entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)
{
zend_string *str = php_stream_copy_to_mem(fp, entry.uncompressed_filesize, 0);
if (str) {
entry.uncompressed_filesize = ZSTR_LEN(str);
actual_alias = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
} else {
actual_alias = NULL;
entry.uncompressed_filesize = 0;
}
}
if (!entry.uncompressed_filesize || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
}
/* return to central directory parsing */
php_stream_seek(fp, saveloc, SEEK_SET);
}
phar_set_inode(&entry);
zend_hash_str_add_mem(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry, sizeof(phar_entry_info));
}
mydata->fp = fp;
if (zend_hash_str_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
mydata->is_data = 0;
} else {
mydata->is_data = 1;
}
zend_hash_str_add_ptr(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len, mydata);
if (actual_alias) {
phar_archive_data *fd_ptr;
if (!phar_validate_alias(actual_alias, mydata->alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: invalid alias \"%s\" in zip-based phar \"%s\"", actual_alias, fname);
}
efree(actual_alias);
zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);
return FAILURE;
}
mydata->is_temporary_alias = 0;
if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len))) {
if (SUCCESS != phar_free_alias(fd_ptr, actual_alias, mydata->alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with implicit alias, alias is already in use", fname);
}
efree(actual_alias);
zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);
return FAILURE;
}
}
mydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias;
if (entry.is_persistent) {
efree(actual_alias);
}
zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata);
} else {
phar_archive_data *fd_ptr;
if (alias_len) {
if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) {
if (SUCCESS != phar_free_alias(fd_ptr, alias, alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with explicit alias, alias is already in use", fname);
}
zend_hash_str_del(&(PHAR_G(phar_fname_map)), mydata->fname, fname_len);
return FAILURE;
}
}
zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, mydata->alias_len, mydata);
mydata->alias = pestrndup(alias, alias_len, mydata->is_persistent);
mydata->alias_len = alias_len;
} else {
mydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent);
mydata->alias_len = fname_len;
}
mydata->is_temporary_alias = 1;
}
if (pphar) {
*pphar = mydata;
}
return SUCCESS;
}
|
CWE-119
| 0
|
1
|
std::vector<GetLengthType> CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target)
{
std::vector<GetLengthType> results;
GetLengthType retval;
retval.startOrder = target.startOrder;
retval.startRow = target.startRow;
const bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget;
const bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions;
SEQUENCEINDEX sequence = target.sequence;
if(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex();
const ModSequence &orderList = Order(sequence);
GetLengthMemory memory(*this);
CSoundFile::PlayState &playState = *memory.state;
RowVisitor visitedRows(*this, sequence);
playState.m_nNextRow = playState.m_nRow = target.startRow;
playState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder;
std::bitset<MAX_EFFECTS> forbiddenCommands;
std::bitset<MAX_VOLCMDS> forbiddenVolCommands;
if(adjustSamplePos)
{
forbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP);
forbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN);
forbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG);
forbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG);
forbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN);
for(CHANNELINDEX i = 0; i < GetNumChannels(); i++)
{
if(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;
}
if(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size())
{
const PATTERNINDEX seekPat = orderList[target.pos.order];
if(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row))
{
const ModCommand *m = Patterns[seekPat].GetRow(target.pos.row);
for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++)
{
if(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments())
|| (m->IsNote() && !m->IsPortamento()))
{
memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;
}
}
}
}
}
uint32 oldTickDuration = 0;
for (;;)
{
if(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time)
{
retval.targetReached = true;
break;
}
uint32 rowDelay = 0, tickDelay = 0;
playState.m_nRow = playState.m_nNextRow;
playState.m_nCurrentOrder = playState.m_nNextOrder;
if(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows())
{
playState.m_nRow = 0;
if(m_playBehaviour[kFT2LoopE60Restart])
{
playState.m_nRow = playState.m_nNextPatStartRow;
playState.m_nNextPatStartRow = 0;
}
playState.m_nCurrentOrder = ++playState.m_nNextOrder;
}
playState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();
bool positionJumpOnThisRow = false;
bool patternBreakOnThisRow = false;
bool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false;
if(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order)
{
retval.targetReached = true;
break;
}
while(playState.m_nPattern >= Patterns.Size())
{
if((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size()))
{
if(playState.m_nCurrentOrder == orderList.GetRestartPos())
break;
else
playState.m_nCurrentOrder = orderList.GetRestartPos();
} else
{
playState.m_nCurrentOrder++;
}
playState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();
playState.m_nNextOrder = playState.m_nCurrentOrder;
if((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true))
{
if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))
{
break;
} else
{
retval.duration = memory.elapsedTime;
results.push_back(retval);
retval.startRow = playState.m_nRow;
retval.startOrder = playState.m_nNextOrder;
memory.Reset();
playState.m_nCurrentOrder = playState.m_nNextOrder;
playState.m_nPattern = orderList[playState.m_nCurrentOrder];
playState.m_nNextRow = playState.m_nRow;
break;
}
}
}
if(playState.m_nNextOrder == ORDERINDEX_INVALID)
{
break;
}
if(!Patterns.IsValidPat(playState.m_nPattern))
{
if(playState.m_nCurrentOrder == orderList.GetRestartPos())
{
if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))
{
break;
} else
{
retval.duration = memory.elapsedTime;
results.push_back(retval);
retval.startRow = playState.m_nRow;
retval.startOrder = playState.m_nNextOrder;
memory.Reset();
playState.m_nNextRow = playState.m_nRow;
continue;
}
}
playState.m_nNextOrder = playState.m_nCurrentOrder + 1;
continue;
}
if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())
playState.m_nRow = 0;
if(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row)
{
retval.targetReached = true;
break;
}
if(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true))
{
if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))
{
break;
} else
{
retval.duration = memory.elapsedTime;
results.push_back(retval);
retval.startRow = playState.m_nRow;
retval.startOrder = playState.m_nNextOrder;
memory.Reset();
playState.m_nNextRow = playState.m_nRow;
continue;
}
}
retval.endOrder = playState.m_nCurrentOrder;
retval.endRow = playState.m_nRow;
playState.m_nNextRow = playState.m_nRow + 1;
if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())
{
playState.m_nRow = 0;
}
if(!playState.m_nRow)
{
for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)
{
memory.chnSettings[chn].patLoop = memory.elapsedTime;
memory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount;
}
}
ModChannel *pChn = playState.Chn;
const ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0);
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++)
{
if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels
continue;
if(p->IsPcNote())
{
#ifndef NO_PLUGINS
if((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS)
{
memory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol();
}
#endif // NO_PLUGINS
pChn[nChn].rowCommand.Clear();
continue;
}
pChn[nChn].rowCommand = *p;
switch(p->command)
{
case CMD_SPEED:
SetSpeed(playState, p->param);
break;
case CMD_TEMPO:
if(m_playBehaviour[kMODVBlankTiming])
{
if(p->param != 0) SetSpeed(playState, p->param);
}
break;
case CMD_S3MCMDEX:
if((p->param & 0xF0) == 0x60)
{
tickDelay += (p->param & 0x0F);
} else if((p->param & 0xF0) == 0xE0 && !rowDelay)
{
if(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0)
{
rowDelay = 1 + (p->param & 0x0F);
}
}
break;
case CMD_MODCMDEX:
if((p->param & 0xF0) == 0xE0)
{
rowDelay = 1 + (p->param & 0x0F);
}
break;
}
}
if(rowDelay == 0) rowDelay = 1;
const uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay;
const uint32 nonRowTicks = numTicks - rowDelay;
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty())
{
if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels
continue;
ModCommand::COMMAND command = pChn->rowCommand.command;
ModCommand::PARAM param = pChn->rowCommand.param;
ModCommand::NOTE note = pChn->rowCommand.note;
if (pChn->rowCommand.instr)
{
pChn->nNewIns = pChn->rowCommand.instr;
pChn->nLastNote = NOTE_NONE;
memory.chnSettings[nChn].vol = 0xFF;
}
if (pChn->rowCommand.IsNote()) pChn->nLastNote = note;
if(pChn->rowCommand.IsNote() || pChn->rowCommand.instr)
{
SAMPLEINDEX smp = 0;
if(GetNumInstruments())
{
ModInstrument *pIns;
if(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr)
{
if(pIns->dwFlags[INS_SETPANNING])
pChn->nPan = pIns->nPan;
if(ModCommand::IsNote(note))
smp = pIns->Keyboard[note - NOTE_MIN];
}
} else
{
smp = pChn->nNewIns;
}
if(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING])
{
pChn->nPan = Samples[smp].nPan;
}
}
switch(pChn->rowCommand.volcmd)
{
case VOLCMD_VOLUME:
memory.chnSettings[nChn].vol = pChn->rowCommand.vol;
break;
case VOLCMD_VOLSLIDEUP:
case VOLCMD_VOLSLIDEDOWN:
if(pChn->rowCommand.vol != 0)
pChn->nOldVolParam = pChn->rowCommand.vol;
break;
}
switch(command)
{
case CMD_POSITIONJUMP:
positionJumpOnThisRow = true;
playState.m_nNextOrder = static_cast<ORDERINDEX>(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn));
playState.m_nNextPatStartRow = 0; // FT2 E60 bug
if(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)))
playState.m_nNextRow = 0;
if (adjustMode & eAdjust)
{
pChn->nPatternLoopCount = 0;
pChn->nPatternLoop = 0;
}
break;
case CMD_PATTERNBREAK:
{
ROWINDEX row = PatternBreak(playState, nChn, param);
if(row != ROWINDEX_INVALID)
{
patternBreakOnThisRow = true;
playState.m_nNextRow = row;
if(!positionJumpOnThisRow)
{
playState.m_nNextOrder = playState.m_nCurrentOrder + 1;
}
if(adjustMode & eAdjust)
{
pChn->nPatternLoopCount = 0;
pChn->nPatternLoop = 0;
}
}
}
break;
case CMD_TEMPO:
if(!m_playBehaviour[kMODVBlankTiming])
{
TEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0);
if ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))
{
if (tempo.GetInt()) pChn->nOldTempo = static_cast<uint8>(tempo.GetInt()); else tempo.Set(pChn->nOldTempo);
}
if (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo;
else
{
TEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0);
if ((tempo.GetInt() & 0xF0) == 0x10)
{
playState.m_nMusicTempo += tempoDiff;
} else
{
if(tempoDiff < playState.m_nMusicTempo)
playState.m_nMusicTempo -= tempoDiff;
else
playState.m_nMusicTempo.Set(0);
}
}
TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax();
if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode
{
tempoMax.Set(255);
}
Limit(playState.m_nMusicTempo, tempoMin, tempoMax);
}
break;
case CMD_S3MCMDEX:
switch(param & 0xF0)
{
case 0x90:
if(param <= 0x91)
{
pChn->dwFlags.set(CHN_SURROUND, param == 0x91);
}
break;
case 0xA0:
pChn->nOldHiOffset = param & 0x0F;
break;
case 0xB0:
if (param & 0x0F)
{
patternLoopEndedOnThisRow = true;
} else
{
CHANNELINDEX firstChn = nChn, lastChn = nChn;
if(GetType() == MOD_TYPE_S3M)
{
firstChn = 0;
lastChn = GetNumChannels() - 1;
}
for(CHANNELINDEX c = firstChn; c <= lastChn; c++)
{
memory.chnSettings[c].patLoop = memory.elapsedTime;
memory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount;
memory.chnSettings[c].patLoopStart = playState.m_nRow;
}
patternLoopStartedOnThisRow = true;
}
break;
case 0xF0:
pChn->nActiveMacro = param & 0x0F;
break;
}
break;
case CMD_MODCMDEX:
switch(param & 0xF0)
{
case 0x60:
if (param & 0x0F)
{
playState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug
patternLoopEndedOnThisRow = true;
} else
{
patternLoopStartedOnThisRow = true;
memory.chnSettings[nChn].patLoop = memory.elapsedTime;
memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;
memory.chnSettings[nChn].patLoopStart = playState.m_nRow;
}
break;
case 0xF0:
pChn->nActiveMacro = param & 0x0F;
break;
}
break;
case CMD_XFINEPORTAUPDOWN:
if(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F;
break;
}
if (!(adjustMode & eAdjust)) continue;
switch(command)
{
case CMD_PORTAMENTOUP:
if(param)
{
if(!m_playBehaviour[kFT2PortaUpDownMemory])
pChn->nOldPortaDown = param;
pChn->nOldPortaUp = param;
}
break;
case CMD_PORTAMENTODOWN:
if(param)
{
if(!m_playBehaviour[kFT2PortaUpDownMemory])
pChn->nOldPortaUp = param;
pChn->nOldPortaDown = param;
}
break;
case CMD_TONEPORTAMENTO:
if (param) pChn->nPortamentoSlide = param << 2;
break;
case CMD_OFFSET:
if (param) pChn->oldOffset = param << 8;
break;
case CMD_VOLUMESLIDE:
case CMD_TONEPORTAVOL:
if (param) pChn->nOldVolumeSlide = param;
break;
case CMD_VOLUME:
memory.chnSettings[nChn].vol = param;
break;
case CMD_GLOBALVOLUME:
if(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2;
if(param <= 128)
{
playState.m_nGlobalVolume = param * 2;
} else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M)))
{
playState.m_nGlobalVolume = 256;
}
break;
case CMD_GLOBALVOLSLIDE:
if(m_playBehaviour[kPerChannelGlobalVolSlide])
{
if (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide;
} else
{
if (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide;
}
if (((param & 0x0F) == 0x0F) && (param & 0xF0))
{
param >>= 4;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
playState.m_nGlobalVolume += param << 1;
} else if (((param & 0xF0) == 0xF0) && (param & 0x0F))
{
param = (param & 0x0F) << 1;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
playState.m_nGlobalVolume -= param;
} else if (param & 0xF0)
{
param >>= 4;
param <<= 1;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
playState.m_nGlobalVolume += param * nonRowTicks;
} else
{
param = (param & 0x0F) << 1;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
playState.m_nGlobalVolume -= param * nonRowTicks;
}
Limit(playState.m_nGlobalVolume, 0, 256);
break;
case CMD_CHANNELVOLUME:
if (param <= 64) pChn->nGlobalVol = param;
break;
case CMD_CHANNELVOLSLIDE:
{
if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide;
int32 volume = pChn->nGlobalVol;
if((param & 0x0F) == 0x0F && (param & 0xF0))
volume += (param >> 4); // Fine Up
else if((param & 0xF0) == 0xF0 && (param & 0x0F))
volume -= (param & 0x0F); // Fine Down
else if(param & 0x0F) // Down
volume -= (param & 0x0F) * nonRowTicks;
else // Up
volume += ((param & 0xF0) >> 4) * nonRowTicks;
Limit(volume, 0, 64);
pChn->nGlobalVol = volume;
}
break;
case CMD_PANNING8:
Panning(pChn, param, Pan8bit);
break;
case CMD_MODCMDEX:
if(param < 0x10)
{
for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)
{
playState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1));
}
}
MPT_FALLTHROUGH;
case CMD_S3MCMDEX:
if((param & 0xF0) == 0x80)
{
Panning(pChn, (param & 0x0F), Pan4bit);
}
break;
case CMD_VIBRATOVOL:
if (param) pChn->nOldVolumeSlide = param;
param = 0;
MPT_FALLTHROUGH;
case CMD_VIBRATO:
Vibrato(pChn, param);
break;
case CMD_FINEVIBRATO:
FineVibrato(pChn, param);
break;
case CMD_TREMOLO:
Tremolo(pChn, param);
break;
case CMD_PANBRELLO:
Panbrello(pChn, param);
break;
}
switch(pChn->rowCommand.volcmd)
{
case VOLCMD_PANNING:
Panning(pChn, pChn->rowCommand.vol, Pan6bit);
break;
case VOLCMD_VIBRATOSPEED:
if(m_playBehaviour[kFT2VolColVibrato])
pChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F;
else
Vibrato(pChn, pChn->rowCommand.vol << 4);
break;
case VOLCMD_VIBRATODEPTH:
Vibrato(pChn, pChn->rowCommand.vol);
break;
}
switch(pChn->rowCommand.command)
{
case CMD_VIBRATO:
case CMD_FINEVIBRATO:
case CMD_VIBRATOVOL:
if(adjustMode & eAdjust)
{
uint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;
uint32 inc = pChn->nVibratoSpeed * vibTicks;
if(m_playBehaviour[kITVibratoTremoloPanbrello])
inc *= 4;
pChn->nVibratoPos += static_cast<uint8>(inc);
}
break;
case CMD_TREMOLO:
if(adjustMode & eAdjust)
{
uint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;
uint32 inc = pChn->nTremoloSpeed * tremTicks;
if(m_playBehaviour[kITVibratoTremoloPanbrello])
inc *= 4;
pChn->nTremoloPos += static_cast<uint8>(inc);
}
break;
case CMD_PANBRELLO:
if(adjustMode & eAdjust)
{
pChn->nPanbrelloPos += static_cast<uint8>(pChn->nPanbrelloSpeed * (numTicks - 1));
ProcessPanbrello(pChn);
}
break;
}
}
if(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max)
{
break;
}
playState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat;
if(Patterns[playState.m_nPattern].GetOverrideSignature())
{
playState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat();
}
const uint32 tickDuration = GetTickDuration(playState);
const uint32 rowDuration = tickDuration * numTicks;
memory.elapsedTime += static_cast<double>(rowDuration) / static_cast<double>(m_MixerSettings.gdwMixingFreq);
playState.m_lTotalSampleCount += rowDuration;
if(adjustSamplePos)
{
pChn = playState.Chn;
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++)
{
if(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL)
continue;
uint32 startTick = 0;
const ModCommand &m = pChn->rowCommand;
uint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F;
bool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO;
bool stopNote = patternLoopStartedOnThisRow; // It's too much trouble to keep those pattern loops in sync...
if(m.instr) pChn->proTrackerOffset = 0;
if(m.IsNote())
{
if(porta && memory.chnSettings[nChn].incChanged)
{
pChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0);
}
int32 setPan = pChn->nPan;
pChn->nNewNote = pChn->nLastNote;
if(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta);
NoteChange(pChn, m.note, porta);
memory.chnSettings[nChn].incChanged = true;
if((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks)
{
startTick = paramLo;
} else if(m.command == CMD_DELAYCUT && paramHi < numTicks)
{
startTick = paramHi;
}
if(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))
{
startTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1);
}
if(!porta) memory.chnSettings[nChn].ticksToRender = 0;
if(m.command == CMD_PANNING8
|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8)
|| m.volcmd == VOLCMD_PANNING)
{
pChn->nPan = setPan;
}
if(m.command == CMD_OFFSET)
{
bool isExtended = false;
SmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended);
if(!isExtended)
{
offset <<= 8;
if(offset == 0) offset = pChn->oldOffset;
offset += static_cast<SmpLength>(pChn->nOldHiOffset) << 16;
}
SampleOffset(*pChn, offset);
} else if(m.command == CMD_OFFSETPERCENTAGE)
{
SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255));
} else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr)
{
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
ReverseSampleOffset(*pChn, m.param);
startTick = playState.m_nMusicSpeed - 1;
} else if(m.volcmd == VOLCMD_OFFSET)
{
if(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr)
{
SmpLength offset;
if(m.vol == 0)
offset = pChn->oldOffset;
else
offset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1];
SampleOffset(*pChn, offset);
}
}
}
if(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments())
|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks)
|| (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks))
{
stopNote = true;
}
if(m.command == CMD_VOLUME)
{
pChn->nVolume = m.param * 4;
} else if(m.volcmd == VOLCMD_VOLUME)
{
pChn->nVolume = m.vol * 4;
}
if(pChn->pModSample && !stopNote)
{
if(m.command < MAX_EFFECTS)
{
if(forbiddenCommands[m.command])
{
stopNote = true;
} else if(m.command == CMD_MODCMDEX)
{
switch(m.param & 0xF0)
{
case 0x10:
case 0x20:
stopNote = true;
}
}
}
if(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd])
{
stopNote = true;
}
}
if(stopNote)
{
pChn->Stop();
memory.chnSettings[nChn].ticksToRender = 0;
} else
{
if(oldTickDuration != tickDuration && oldTickDuration != 0)
{
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
}
switch(m.command)
{
case CMD_TONEPORTAVOL:
case CMD_VOLUMESLIDE:
case CMD_VIBRATOVOL:
if(m.param || (GetType() != MOD_TYPE_MOD))
{
for(uint32 i = 0; i < numTicks; i++)
{
pChn->isFirstTick = (i == 0);
VolumeSlide(pChn, m.param);
}
}
break;
case CMD_MODCMDEX:
if((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)))
{
pChn->isFirstTick = true;
switch(m.param & 0xF0)
{
case 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break;
case 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break;
}
}
break;
case CMD_S3MCMDEX:
if(m.param == 0x9E)
{
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
pChn->dwFlags.reset(CHN_PINGPONGFLAG);
} else if(m.param == 0x9F)
{
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
pChn->dwFlags.set(CHN_PINGPONGFLAG);
if(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP]))
{
pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax);
}
} else if((m.param & 0xF0) == 0x70)
{
}
break;
}
pChn->isFirstTick = true;
switch(m.volcmd)
{
case VOLCMD_FINEVOLUP: FineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;
case VOLCMD_FINEVOLDOWN: FineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;
case VOLCMD_VOLSLIDEUP:
case VOLCMD_VOLSLIDEDOWN:
{
ModCommand::VOL vol = m.vol;
if(vol == 0 && m_playBehaviour[kITVolColMemory])
{
vol = pChn->nOldVolParam;
if(vol == 0)
break;
}
if(m.volcmd == VOLCMD_VOLSLIDEUP)
vol <<= 4;
for(uint32 i = 0; i < numTicks; i++)
{
pChn->isFirstTick = (i == 0);
VolumeSlide(pChn, vol);
}
}
break;
}
if(porta)
{
uint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1;
memory.chnSettings[nChn].ticksToRender += numTicks;
memory.RenderChannel(nChn, tickDuration, portaTick);
} else
{
memory.chnSettings[nChn].ticksToRender += (numTicks - startTick);
}
}
}
}
oldTickDuration = tickDuration;
if(patternLoopEndedOnThisRow
&& (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow))
&& (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow))
{
std::map<double, int> startTimes;
pChn = playState.Chn;
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)
{
ModCommand::COMMAND command = pChn->rowCommand.command;
ModCommand::PARAM param = pChn->rowCommand.param;
if((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF)
|| (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F))
{
const double start = memory.chnSettings[nChn].patLoop;
if(!startTimes[start]) startTimes[start] = 1;
startTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F));
}
}
for(const auto &i : startTimes)
{
memory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1);
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)
{
if(memory.chnSettings[nChn].patLoop == i.first)
{
playState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1);
if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M))
{
memory.chnSettings[nChn].patLoop = memory.elapsedTime;
memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;
memory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1;
}
break;
}
}
}
if(GetType() == MOD_TYPE_IT)
{
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)
{
if((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF))
{
memory.chnSettings[nChn].patLoop = memory.elapsedTime;
memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;
}
}
}
}
}
if(adjustSamplePos)
{
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)
{
if(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL)
{
memory.RenderChannel(nChn, oldTickDuration);
}
}
}
if(retval.targetReached || target.mode == GetLengthTarget::NoTarget)
{
retval.lastOrder = playState.m_nCurrentOrder;
retval.lastRow = playState.m_nRow;
}
retval.duration = memory.elapsedTime;
results.push_back(retval);
if(adjustMode & eAdjust)
{
if(retval.targetReached || target.mode == GetLengthTarget::NoTarget)
{
m_PlayState = std::move(playState);
m_PlayState.m_nNextRow = m_PlayState.m_nRow;
m_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0;
m_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1;
m_PlayState.m_bPositionChanged = true;
for(CHANNELINDEX n = 0; n < GetNumChannels(); n++)
{
if(m_PlayState.Chn[n].nLastNote != NOTE_NONE)
{
m_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote;
}
if(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos)
{
m_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4;
}
}
#ifndef NO_PLUGINS
std::bitset<MAX_MIXPLUGINS> plugSetProgram;
for(const auto ¶m : memory.plugParams)
{
PLUGINDEX plug = param.first.first - 1;
IMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin;
if(plugin != nullptr)
{
if(!plugSetProgram[plug])
{
plugSetProgram.set(plug);
plugin->BeginSetProgram();
}
plugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue));
}
}
if(plugSetProgram.any())
{
for(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++)
{
if(plugSetProgram[i])
{
m_MixPlugins[i].pMixPlugin->EndSetProgram();
}
}
}
#endif // NO_PLUGINS
} else if(adjustMode != eAdjustOnSuccess)
{
m_PlayState.m_nMusicSpeed = m_nDefaultSpeed;
m_PlayState.m_nMusicTempo = m_nDefaultTempo;
m_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume;
}
if(sequence != Order.GetCurrentSequenceIndex())
{
Order.SetSequence(sequence);
}
visitedSongRows.Set(visitedRows);
}
return results;
}
|
CWE-125
| 1
|
1
|
setup_seccomp (FlatpakBwrap *bwrap,
const char *arch,
gulong allowed_personality,
FlatpakRunFlags run_flags,
GError **error)
{
gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0;
gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0;
__attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL;
/**** BEGIN NOTE ON CODE SHARING
*
* There are today a number of different Linux container
* implementations. That will likely continue for long into the
* future. But we can still try to share code, and it's important
* to do so because it affects what library and application writers
* can do, and we should support code portability between different
* container tools.
*
* This syscall blacklist is copied from linux-user-chroot, which was in turn
* clearly influenced by the Sandstorm.io blacklist.
*
* If you make any changes here, I suggest sending the changes along
* to other sandbox maintainers. Using the libseccomp list is also
* an appropriate venue:
* https://groups.google.com/forum/#!topic/libseccomp
*
* A non-exhaustive list of links to container tooling that might
* want to share this blacklist:
*
* https://github.com/sandstorm-io/sandstorm
* in src/sandstorm/supervisor.c++
* https://github.com/flatpak/flatpak.git
* in common/flatpak-run.c
* https://git.gnome.org/browse/linux-user-chroot
* in src/setup-seccomp.c
*
**** END NOTE ON CODE SHARING
*/
struct
{
int scall;
struct scmp_arg_cmp *arg;
} syscall_blacklist[] = {
/* Block dmesg */
{SCMP_SYS (syslog)},
/* Useless old syscall */
{SCMP_SYS (uselib)},
/* Don't allow disabling accounting */
{SCMP_SYS (acct)},
/* 16-bit code is unnecessary in the sandbox, and modify_ldt is a
historic source of interesting information leaks. */
{SCMP_SYS (modify_ldt)},
/* Don't allow reading current quota use */
{SCMP_SYS (quotactl)},
/* Don't allow access to the kernel keyring */
{SCMP_SYS (add_key)},
{SCMP_SYS (keyctl)},
{SCMP_SYS (request_key)},
/* Scary VM/NUMA ops */
{SCMP_SYS (move_pages)},
{SCMP_SYS (mbind)},
{SCMP_SYS (get_mempolicy)},
{SCMP_SYS (set_mempolicy)},
{SCMP_SYS (migrate_pages)},
/* Don't allow subnamespace setups: */
{SCMP_SYS (unshare)},
{SCMP_SYS (mount)},
{SCMP_SYS (pivot_root)},
{SCMP_SYS (clone), &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},
/* Don't allow faking input to the controlling tty (CVE-2017-5226) */
{SCMP_SYS (ioctl), &SCMP_A1 (SCMP_CMP_EQ, (int) TIOCSTI)},
};
struct
{
int scall;
struct scmp_arg_cmp *arg;
} syscall_nondevel_blacklist[] = {
/* Profiling operations; we expect these to be done by tools from outside
* the sandbox. In particular perf has been the source of many CVEs.
*/
{SCMP_SYS (perf_event_open)},
/* Don't allow you to switch to bsd emulation or whatnot */
{SCMP_SYS (personality), &SCMP_A0 (SCMP_CMP_NE, allowed_personality)},
{SCMP_SYS (ptrace)}
};
/* Blacklist all but unix, inet, inet6 and netlink */
struct
{
int family;
FlatpakRunFlags flags_mask;
} socket_family_whitelist[] = {
/* NOTE: Keep in numerical order */
{ AF_UNSPEC, 0 },
{ AF_LOCAL, 0 },
{ AF_INET, 0 },
{ AF_INET6, 0 },
{ AF_NETLINK, 0 },
{ AF_CAN, FLATPAK_RUN_FLAG_CANBUS },
{ AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH },
};
int last_allowed_family;
int i, r;
g_auto(GLnxTmpfile) seccomp_tmpf = { 0, };
seccomp = seccomp_init (SCMP_ACT_ALLOW);
if (!seccomp)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Initialize seccomp failed"));
if (arch != NULL)
{
uint32_t arch_id = 0;
const uint32_t *extra_arches = NULL;
if (strcmp (arch, "i386") == 0)
{
arch_id = SCMP_ARCH_X86;
}
else if (strcmp (arch, "x86_64") == 0)
{
arch_id = SCMP_ARCH_X86_64;
extra_arches = seccomp_x86_64_extra_arches;
}
else if (strcmp (arch, "arm") == 0)
{
arch_id = SCMP_ARCH_ARM;
}
#ifdef SCMP_ARCH_AARCH64
else if (strcmp (arch, "aarch64") == 0)
{
arch_id = SCMP_ARCH_AARCH64;
extra_arches = seccomp_aarch64_extra_arches;
}
#endif
/* We only really need to handle arches on multiarch systems.
* If only one arch is supported the default is fine */
if (arch_id != 0)
{
/* This *adds* the target arch, instead of replacing the
native one. This is not ideal, because we'd like to only
allow the target arch, but we can't really disallow the
native arch at this point, because then bubblewrap
couldn't continue running. */
r = seccomp_arch_add (seccomp, arch_id);
if (r < 0 && r != -EEXIST)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to add architecture to seccomp filter"));
if (multiarch && extra_arches != NULL)
{
unsigned i;
for (i = 0; extra_arches[i] != 0; i++)
{
r = seccomp_arch_add (seccomp, extra_arches[i]);
if (r < 0 && r != -EEXIST)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to add multiarch architecture to seccomp filter"));
}
}
}
}
/* TODO: Should we filter the kernel keyring syscalls in some way?
* We do want them to be used by desktop apps, but they could also perhaps
* leak system stuff or secrets from other apps.
*/
for (i = 0; i < G_N_ELEMENTS (syscall_blacklist); i++)
{
int scall = syscall_blacklist[i].scall;
if (syscall_blacklist[i].arg)
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_blacklist[i].arg);
else
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);
if (r < 0 && r == -EFAULT /* unknown syscall */)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to block syscall %d"), scall);
}
if (!devel)
{
for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blacklist); i++)
{
int scall = syscall_nondevel_blacklist[i].scall;
if (syscall_nondevel_blacklist[i].arg)
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_nondevel_blacklist[i].arg);
else
r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);
if (r < 0 && r == -EFAULT /* unknown syscall */)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to block syscall %d"), scall);
}
}
/* Socket filtering doesn't work on e.g. i386, so ignore failures here
* However, we need to user seccomp_rule_add_exact to avoid libseccomp doing
* something else: https://github.com/seccomp/libseccomp/issues/8 */
last_allowed_family = -1;
for (i = 0; i < G_N_ELEMENTS (socket_family_whitelist); i++)
{
int family = socket_family_whitelist[i].family;
int disallowed;
if (socket_family_whitelist[i].flags_mask != 0 &&
(socket_family_whitelist[i].flags_mask & run_flags) != socket_family_whitelist[i].flags_mask)
continue;
for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++)
{
/* Blacklist the in-between valid families */
seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed));
}
last_allowed_family = family;
}
/* Blacklist the rest */
seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1));
if (!glnx_open_anonymous_tmpfile (O_RDWR | O_CLOEXEC, &seccomp_tmpf, error))
return FALSE;
if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0)
return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _("Failed to export bpf"));
lseek (seccomp_tmpf.fd, 0, SEEK_SET);
flatpak_bwrap_add_args_data_fd (bwrap,
"--seccomp", glnx_steal_fd (&seccomp_tmpf.fd), NULL);
return TRUE;
}
|
CWE-20
| 2
|
0
|
static void add_capability(uint32_t **caps, int *num_caps, uint32_t cap)
{
int nbefore, n;
nbefore = *num_caps;
n = cap / 32;
*num_caps = MAX(*num_caps, n + 1);
*caps = spice_renew(uint32_t, *caps, *num_caps);
memset(*caps + nbefore, 0, (*num_caps - nbefore) * sizeof(uint32_t));
(*caps)[n] |= (1 << (cap % 32));
}
|
none
| 8
|
1
|
static void buffer_pipe_buf_get(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
struct buffer_ref *ref = (struct buffer_ref *)buf->private;
ref->ref++;
}
|
CWE-416
| 5
|
0
|
GfxDeviceNColorSpace::~GfxDeviceNColorSpace() {
int i;
for (i = 0; i < nComps; ++i) {
delete names[i];
}
delete alt;
delete func;
}
|
none
| 8
|
0
|
static inline Guchar div255(int x) {
return (Guchar)((x + (x >> 8) + 0x80) >> 8);
}
|
none
| 8
|
0
|
inline void Splash::updateModX(int x) {
if (x < modXMin) {
modXMin = x;
}
if (x > modXMax) {
modXMax = x;
}
}
|
none
| 8
|
1
|
dictionary * iniparser_load(const char * ininame)
{
FILE * in ;
char line [ASCIILINESZ+1] ;
char section [ASCIILINESZ+1] ;
char key [ASCIILINESZ+1] ;
char tmp [(ASCIILINESZ * 2) + 1] ;
char val [ASCIILINESZ+1] ;
int last=0 ;
int len ;
int lineno=0 ;
int errs=0;
dictionary * dict ;
if ((in=fopen(ininame, "r"))==NULL) {
fprintf(stderr, "iniparser: cannot open %s\n", ininame);
return NULL ;
}
dict = dictionary_new(0) ;
if (!dict) {
fclose(in);
return NULL ;
}
memset(line, 0, ASCIILINESZ);
memset(section, 0, ASCIILINESZ);
memset(key, 0, ASCIILINESZ);
memset(val, 0, ASCIILINESZ);
last=0 ;
while (fgets(line+last, ASCIILINESZ-last, in)!=NULL) {
lineno++ ;
len = (int)strlen(line)-1;
if (len==0)
continue;
/* Safety check against buffer overflows */
if (line[len]!='\n' && !feof(in)) {
fprintf(stderr,
"iniparser: input line too long in %s (%d)\n",
ininame,
lineno);
dictionary_del(dict);
fclose(in);
return NULL ;
}
/* Get rid of \n and spaces at end of line */
while ((len>=0) &&
((line[len]=='\n') || (isspace(line[len])))) {
line[len]=0 ;
len-- ;
}
if (len < 0) { /* Line was entirely \n and/or spaces */
len = 0;
}
/* Detect multi-line */
if (line[len]=='\\') {
/* Multi-line value */
last=len ;
continue ;
} else {
last=0 ;
}
switch (iniparser_line(line, section, key, val)) {
case LINE_EMPTY:
case LINE_COMMENT:
break ;
case LINE_SECTION:
errs = dictionary_set(dict, section, NULL);
break ;
case LINE_VALUE:
sprintf(tmp, "%s:%s", section, key);
errs = dictionary_set(dict, tmp, val) ;
break ;
case LINE_ERROR:
fprintf(stderr, "iniparser: syntax error in %s (%d):\n",
ininame,
lineno);
fprintf(stderr, "-> %s\n", line);
errs++ ;
break;
default:
break ;
}
memset(line, 0, ASCIILINESZ);
last=0;
if (errs<0) {
fprintf(stderr, "iniparser: memory allocation failure\n");
break ;
}
}
if (errs) {
dictionary_del(dict);
dict = NULL ;
}
fclose(in);
return dict ;
}
|
CWE-200
| 3
|
0
|
SplashError Splash::blitTransparent(SplashBitmap *src, int xSrc, int ySrc,
int xDest, int yDest, int w, int h) {
SplashColor pixel;
SplashColorPtr p;
Guchar *q;
int x, y, mask;
if (src->mode != bitmap->mode) {
return splashErrModeMismatch;
}
switch (bitmap->mode) {
case splashModeMono1:
for (y = 0; y < h; ++y) {
p = &bitmap->data[(yDest + y) * bitmap->rowSize + (xDest >> 3)];
mask = 0x80 >> (xDest & 7);
for (x = 0; x < w; ++x) {
src->getPixel(xSrc + x, ySrc + y, pixel);
if (pixel[0]) {
*p |= mask;
} else {
*p &= ~mask;
}
if (!(mask >>= 1)) {
mask = 0x80;
++p;
}
}
}
break;
case splashModeMono8:
for (y = 0; y < h; ++y) {
p = &bitmap->data[(yDest + y) * bitmap->rowSize + xDest];
for (x = 0; x < w; ++x) {
src->getPixel(xSrc + x, ySrc + y, pixel);
*p++ = pixel[0];
}
}
break;
case splashModeRGB8:
case splashModeBGR8:
for (y = 0; y < h; ++y) {
p = &bitmap->data[(yDest + y) * bitmap->rowSize + 3 * xDest];
for (x = 0; x < w; ++x) {
src->getPixel(xSrc + x, ySrc + y, pixel);
*p++ = pixel[0];
*p++ = pixel[1];
*p++ = pixel[2];
}
}
break;
case splashModeXBGR8:
for (y = 0; y < h; ++y) {
p = &bitmap->data[(yDest + y) * bitmap->rowSize + 4 * xDest];
for (x = 0; x < w; ++x) {
src->getPixel(xSrc + x, ySrc + y, pixel);
*p++ = pixel[0];
*p++ = pixel[1];
*p++ = pixel[2];
*p++ = 255;
}
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
for (y = 0; y < h; ++y) {
p = &bitmap->data[(yDest + y) * bitmap->rowSize + 4 * xDest];
for (x = 0; x < w; ++x) {
src->getPixel(xSrc + x, ySrc + y, pixel);
*p++ = pixel[0];
*p++ = pixel[1];
*p++ = pixel[2];
*p++ = pixel[3];
}
}
break;
#endif
}
if (bitmap->alpha) {
for (y = 0; y < h; ++y) {
q = &bitmap->alpha[(yDest + y) * bitmap->width + xDest];
for (x = 0; x < w; ++x) {
*q++ = 0x00;
}
}
}
return splashOk;
}
|
none
| 8
|
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
| 5
|
0
|
void SplashOutputDev::clearSoftMask(GfxState * /*state*/) {
splash->setSoftMask(NULL);
}
|
none
| 8
|
0
|
void GfxImageColorMap::getGray(Guchar *x, GfxGray *gray) {
GfxColor color;
int i;
if (colorSpace2) {
for (i = 0; i < nComps2; ++i) {
color.c[i] = lookup[i][x[0]];
}
colorSpace2->getGray(&color, gray);
} else {
for (i = 0; i < nComps; ++i) {
color.c[i] = lookup[i][x[i]];
}
colorSpace->getGray(&color, gray);
}
}
|
none
| 8
|
0
|
GfxTilingPattern *GfxTilingPattern::parse(Object *patObj) {
GfxTilingPattern *pat;
Dict *dict;
int paintTypeA, tilingTypeA;
double bboxA[4], matrixA[6];
double xStepA, yStepA;
Object resDictA;
Object obj1, obj2;
int i;
if (!patObj->isStream()) {
return NULL;
}
dict = patObj->streamGetDict();
if (dict->lookup("PaintType", &obj1)->isInt()) {
paintTypeA = obj1.getInt();
} else {
paintTypeA = 1;
error(-1, "Invalid or missing PaintType in pattern");
}
obj1.free();
if (dict->lookup("TilingType", &obj1)->isInt()) {
tilingTypeA = obj1.getInt();
} else {
tilingTypeA = 1;
error(-1, "Invalid or missing TilingType in pattern");
}
obj1.free();
bboxA[0] = bboxA[1] = 0;
bboxA[2] = bboxA[3] = 1;
if (dict->lookup("BBox", &obj1)->isArray() &&
obj1.arrayGetLength() == 4) {
for (i = 0; i < 4; ++i) {
if (obj1.arrayGet(i, &obj2)->isNum()) {
bboxA[i] = obj2.getNum();
}
obj2.free();
}
} else {
error(-1, "Invalid or missing BBox in pattern");
}
obj1.free();
if (dict->lookup("XStep", &obj1)->isNum()) {
xStepA = obj1.getNum();
} else {
xStepA = 1;
error(-1, "Invalid or missing XStep in pattern");
}
obj1.free();
if (dict->lookup("YStep", &obj1)->isNum()) {
yStepA = obj1.getNum();
} else {
yStepA = 1;
error(-1, "Invalid or missing YStep in pattern");
}
obj1.free();
if (!dict->lookup("Resources", &resDictA)->isDict()) {
resDictA.free();
resDictA.initNull();
error(-1, "Invalid or missing Resources in pattern");
}
matrixA[0] = 1; matrixA[1] = 0;
matrixA[2] = 0; matrixA[3] = 1;
matrixA[4] = 0; matrixA[5] = 0;
if (dict->lookup("Matrix", &obj1)->isArray() &&
obj1.arrayGetLength() == 6) {
for (i = 0; i < 6; ++i) {
if (obj1.arrayGet(i, &obj2)->isNum()) {
matrixA[i] = obj2.getNum();
}
obj2.free();
}
}
obj1.free();
pat = new GfxTilingPattern(paintTypeA, tilingTypeA, bboxA, xStepA, yStepA,
&resDictA, matrixA, patObj);
resDictA.free();
return pat;
}
|
none
| 8
|
1
|
void exit_mmap(struct mm_struct *mm)
{
struct mmu_gather tlb;
struct vm_area_struct *vma;
unsigned long nr_accounted = 0;
/* mm's last user has gone, and its about to be pulled down */
mmu_notifier_release(mm);
if (mm->locked_vm) {
vma = mm->mmap;
while (vma) {
if (vma->vm_flags & VM_LOCKED)
munlock_vma_pages_all(vma);
vma = vma->vm_next;
}
}
arch_exit_mmap(mm);
vma = mm->mmap;
if (!vma) /* Can happen if dup_mmap() received an OOM */
return;
lru_add_drain();
flush_cache_mm(mm);
tlb_gather_mmu(&tlb, mm, 0, -1);
/* update_hiwater_rss(mm) here? but nobody should be looking */
/* Use -1 here to ensure all VMAs in the mm are unmapped */
unmap_vmas(&tlb, vma, 0, -1);
if (unlikely(mm_is_oom_victim(mm))) {
/*
* Wait for oom_reap_task() to stop working on this
* mm. Because MMF_OOM_SKIP is already set before
* calling down_read(), oom_reap_task() will not run
* on this "mm" post up_write().
*
* mm_is_oom_victim() cannot be set from under us
* either because victim->mm is already set to NULL
* under task_lock before calling mmput and oom_mm is
* set not NULL by the OOM killer only if victim->mm
* is found not NULL while holding the task_lock.
*/
set_bit(MMF_OOM_SKIP, &mm->flags);
down_write(&mm->mmap_sem);
up_write(&mm->mmap_sem);
}
free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
tlb_finish_mmu(&tlb, 0, -1);
/*
* Walk the list again, actually closing and freeing it,
* with preemption enabled, without holding any MM locks.
*/
while (vma) {
if (vma->vm_flags & VM_ACCOUNT)
nr_accounted += vma_pages(vma);
vma = remove_vma(vma);
}
vm_unacct_memory(nr_accounted);
}
|
CWE-476
| 6
|
0
|
void red_channel_client_init_send_data(RedChannelClient *rcc, uint16_t msg_type, PipeItem *item)
{
spice_assert(red_channel_client_no_item_being_sent(rcc));
spice_assert(msg_type != 0);
rcc->send_data.header.set_msg_type(&rcc->send_data.header, msg_type);
rcc->send_data.item = item;
if (item) {
rcc->channel->channel_cbs.hold_item(rcc, item);
}
}
|
none
| 8
|
1
|
static int h2c_decode_headers(struct h2c *h2c, struct buffer *rxbuf, uint32_t *flags)
{
const uint8_t *hdrs = (uint8_t *)b_head(&h2c->dbuf);
struct buffer *tmp = get_trash_chunk();
struct http_hdr list[MAX_HTTP_HDR * 2];
struct buffer *copy = NULL;
unsigned int msgf;
struct htx *htx = NULL;
int flen; // header frame len
int hole = 0;
int ret = 0;
int outlen;
int wrap;
int try = 0;
next_frame:
if (b_data(&h2c->dbuf) - hole < h2c->dfl)
goto leave; // incomplete input frame
/* No END_HEADERS means there's one or more CONTINUATION frames. In
* this case, we'll try to paste it immediately after the initial
* HEADERS frame payload and kill any possible padding. The initial
* frame's length will be increased to represent the concatenation
* of the two frames. The next frame is read from position <tlen>
* and written at position <flen> (minus padding if some is present).
*/
if (unlikely(!(h2c->dff & H2_F_HEADERS_END_HEADERS))) {
struct h2_fh hdr;
int clen; // CONTINUATION frame's payload length
if (!h2_peek_frame_hdr(&h2c->dbuf, h2c->dfl + hole, &hdr)) {
/* no more data, the buffer may be full, either due to
* too large a frame or because of too large a hole that
* we're going to compact at the end.
*/
goto leave;
}
if (hdr.ft != H2_FT_CONTINUATION) {
/* RFC7540#6.10: frame of unexpected type */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
goto fail;
}
if (hdr.sid != h2c->dsi) {
/* RFC7540#6.10: frame of different stream */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
goto fail;
}
if ((unsigned)hdr.len > (unsigned)global.tune.bufsize) {
/* RFC7540#4.2: invalid frame length */
h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR);
goto fail;
}
/* detect when we must stop aggragating frames */
h2c->dff |= hdr.ff & H2_F_HEADERS_END_HEADERS;
/* Take as much as we can of the CONTINUATION frame's payload */
clen = b_data(&h2c->dbuf) - (h2c->dfl + hole + 9);
if (clen > hdr.len)
clen = hdr.len;
/* Move the frame's payload over the padding, hole and frame
* header. At least one of hole or dpl is null (see diagrams
* above). The hole moves after the new aggragated frame.
*/
b_move(&h2c->dbuf, b_peek_ofs(&h2c->dbuf, h2c->dfl + hole + 9), clen, -(h2c->dpl + hole + 9));
h2c->dfl += clen - h2c->dpl;
hole += h2c->dpl + 9;
h2c->dpl = 0;
goto next_frame;
}
flen = h2c->dfl - h2c->dpl;
/* if the input buffer wraps, take a temporary copy of it (rare) */
wrap = b_wrap(&h2c->dbuf) - b_head(&h2c->dbuf);
if (wrap < h2c->dfl) {
copy = alloc_trash_chunk();
if (!copy) {
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
goto fail;
}
memcpy(copy->area, b_head(&h2c->dbuf), wrap);
memcpy(copy->area + wrap, b_orig(&h2c->dbuf), h2c->dfl - wrap);
hdrs = (uint8_t *) copy->area;
}
/* Skip StreamDep and weight for now (we don't support PRIORITY) */
if (h2c->dff & H2_F_HEADERS_PRIORITY) {
if (read_n32(hdrs) == h2c->dsi) {
/* RFC7540#5.3.1 : stream dep may not depend on itself */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
goto fail;
}
hdrs += 5; // stream dep = 4, weight = 1
flen -= 5;
}
if (!h2_get_buf(h2c, rxbuf)) {
h2c->flags |= H2_CF_DEM_SALLOC;
goto leave;
}
/* we can't retry a failed decompression operation so we must be very
* careful not to take any risks. In practice the output buffer is
* always empty except maybe for trailers, in which case we simply have
* to wait for the upper layer to finish consuming what is available.
*/
if (h2c->proxy->options2 & PR_O2_USE_HTX) {
htx = htx_from_buf(rxbuf);
if (!htx_is_empty(htx)) {
h2c->flags |= H2_CF_DEM_SFULL;
goto leave;
}
} else {
if (b_data(rxbuf)) {
h2c->flags |= H2_CF_DEM_SFULL;
goto leave;
}
rxbuf->head = 0;
try = b_size(rxbuf);
}
/* past this point we cannot roll back in case of error */
outlen = hpack_decode_frame(h2c->ddht, hdrs, flen, list,
sizeof(list)/sizeof(list[0]), tmp);
if (outlen < 0) {
h2c_error(h2c, H2_ERR_COMPRESSION_ERROR);
goto fail;
}
/* The PACK decompressor was updated, let's update the input buffer and
* the parser's state to commit these changes and allow us to later
* fail solely on the stream if needed.
*/
b_del(&h2c->dbuf, h2c->dfl + hole);
h2c->dfl = hole = 0;
h2c->st0 = H2_CS_FRAME_H;
/* OK now we have our header list in <list> */
msgf = (h2c->dff & H2_F_HEADERS_END_STREAM) ? 0 : H2_MSGF_BODY;
if (*flags & H2_SF_HEADERS_RCVD)
goto trailers;
/* This is the first HEADERS frame so it's a headers block */
if (htx) {
/* HTX mode */
if (h2c->flags & H2_CF_IS_BACK)
outlen = h2_make_htx_response(list, htx, &msgf);
else
outlen = h2_make_htx_request(list, htx, &msgf);
} else {
/* HTTP/1 mode */
outlen = h2_make_h1_request(list, b_tail(rxbuf), try, &msgf);
if (outlen > 0)
b_add(rxbuf, outlen);
}
if (outlen < 0) {
/* too large headers? this is a stream error only */
goto fail;
}
if (msgf & H2_MSGF_BODY) {
/* a payload is present */
if (msgf & H2_MSGF_BODY_CL)
*flags |= H2_SF_DATA_CLEN;
else if (!(msgf & H2_MSGF_BODY_TUNNEL) && !htx)
*flags |= H2_SF_DATA_CHNK;
}
done:
/* indicate that a HEADERS frame was received for this stream */
*flags |= H2_SF_HEADERS_RCVD;
if (h2c->dff & H2_F_HEADERS_END_STREAM) {
/* Mark the end of message, either using EOM in HTX or with the
* trailing CRLF after the end of trailers. Note that DATA_CHNK
* is not set during headers with END_STREAM.
*/
if (htx) {
if (!htx_add_endof(htx, HTX_BLK_EOM))
goto fail;
}
else if (*flags & H2_SF_DATA_CHNK) {
if (!b_putblk(rxbuf, "\r\n", 2))
goto fail;
}
}
/* success */
ret = 1;
leave:
/* If there is a hole left and it's not at the end, we are forced to
* move the remaining data over it.
*/
if (hole) {
if (b_data(&h2c->dbuf) > h2c->dfl + hole)
b_move(&h2c->dbuf, b_peek_ofs(&h2c->dbuf, h2c->dfl + hole),
b_data(&h2c->dbuf) - (h2c->dfl + hole), -hole);
b_sub(&h2c->dbuf, hole);
}
if (b_full(&h2c->dbuf) && h2c->dfl > b_data(&h2c->dbuf)) {
/* too large frames */
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
ret = -1;
}
if (htx)
htx_to_buf(htx, rxbuf);
free_trash_chunk(copy);
return ret;
fail:
ret = -1;
goto leave;
trailers:
/* This is the last HEADERS frame hence a trailer */
if (!(h2c->dff & H2_F_HEADERS_END_STREAM)) {
/* It's a trailer but it's missing ES flag */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
goto fail;
}
/* Trailers terminate a DATA sequence. In HTX we have to emit an EOD
* block, and when using chunks we must send the 0 CRLF marker. For
* other modes, the trailers are silently dropped.
*/
if (htx) {
if (!htx_add_endof(htx, HTX_BLK_EOD))
goto fail;
if (h2_make_htx_trailers(list, htx) <= 0)
goto fail;
}
else if (*flags & H2_SF_DATA_CHNK) {
/* Legacy mode with chunked encoding : we must finalize the
* data block message emit the trailing CRLF */
if (!b_putblk(rxbuf, "0\r\n", 3))
goto fail;
outlen = h2_make_h1_trailers(list, b_tail(rxbuf), try);
if (outlen > 0)
b_add(rxbuf, outlen);
else
goto fail;
}
goto done;
}
|
CWE-125
| 1
|
1
|
jp2_box_t *jp2_box_get(jas_stream_t *in)
{
jp2_box_t *box;
jp2_boxinfo_t *boxinfo;
jas_stream_t *tmpstream;
uint_fast32_t len;
uint_fast64_t extlen;
bool dataflag;
box = 0;
tmpstream = 0;
if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
goto error;
}
box->ops = &jp2_boxinfo_unk.ops;
if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) {
goto error;
}
boxinfo = jp2_boxinfolookup(box->type);
box->info = boxinfo;
box->ops = &boxinfo->ops;
box->len = len;
JAS_DBGLOG(10, (
"preliminary processing of JP2 box: type=%c%s%c (0x%08x); length=%d\n",
'"', boxinfo->name, '"', box->type, box->len
));
if (box->len == 1) {
if (jp2_getuint64(in, &extlen)) {
goto error;
}
if (extlen > 0xffffffffUL) {
jas_eprintf("warning: cannot handle large 64-bit box length\n");
extlen = 0xffffffffUL;
}
box->len = extlen;
box->datalen = extlen - JP2_BOX_HDRLEN(true);
} else {
box->datalen = box->len - JP2_BOX_HDRLEN(false);
}
if (box->len != 0 && box->len < 8) {
goto error;
}
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (jas_stream_copy(tmpstream, in, box->datalen)) {
box->ops = &jp2_boxinfo_unk.ops;
jas_eprintf("cannot copy box data\n");
goto error;
}
jas_stream_rewind(tmpstream);
if (box->ops->getdata) {
if ((*box->ops->getdata)(box, tmpstream)) {
jas_eprintf("cannot parse box data\n");
goto error;
}
}
jas_stream_close(tmpstream);
}
if (jas_getdbglevel() >= 1) {
jp2_box_dump(box, stderr);
}
return box;
error:
if (box) {
jp2_box_destroy(box);
}
if (tmpstream) {
jas_stream_close(tmpstream);
}
return 0;
}
|
CWE-476
| 6
|
0
|
int ssl3_num_ciphers(void)
{
return(SSL3_NUM_CIPHERS);
}
|
none
| 8
|
1
|
xml_element* xml_elem_parse_buf(const char* in_buf, int len, XML_ELEM_INPUT_OPTIONS options, XML_ELEM_ERROR error)
{
xml_element* xReturn = NULL;
char buf[100] = "";
static STRUCT_XML_ELEM_INPUT_OPTIONS default_opts = {encoding_utf_8};
if(!options) {
options = &default_opts;
}
if(in_buf) {
XML_Parser parser;
xml_elem_data mydata = {0};
parser = XML_ParserCreate(NULL);
mydata.root = xml_elem_new();
mydata.current = mydata.root;
mydata.input_options = options;
mydata.needs_enc_conversion = options->encoding && strcmp(options->encoding, encoding_utf_8);
XML_SetElementHandler(parser, (XML_StartElementHandler)_xmlrpc_startElement, (XML_EndElementHandler)_xmlrpc_endElement);
XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler)_xmlrpc_charHandler);
/* pass the xml_elem_data struct along */
XML_SetUserData(parser, (void*)&mydata);
if(!len) {
len = strlen(in_buf);
}
/* parse the XML */
if(XML_Parse(parser, in_buf, len, 1) == 0) {
enum XML_Error err_code = XML_GetErrorCode(parser);
int line_num = XML_GetCurrentLineNumber(parser);
int col_num = XML_GetCurrentColumnNumber(parser);
long byte_idx = XML_GetCurrentByteIndex(parser);
int byte_total = XML_GetCurrentByteCount(parser);
const char * error_str = XML_ErrorString(err_code);
if(byte_idx >= 0) {
snprintf(buf,
sizeof(buf),
"\n\tdata beginning %ld before byte index: %s\n",
byte_idx > 10 ? 10 : byte_idx,
in_buf + (byte_idx > 10 ? byte_idx - 10 : byte_idx));
}
fprintf(stderr, "expat reports error code %i\n"
"\tdescription: %s\n"
"\tline: %i\n"
"\tcolumn: %i\n"
"\tbyte index: %ld\n"
"\ttotal bytes: %i\n%s ",
err_code, error_str, line_num,
col_num, byte_idx, byte_total, buf);
/* error condition */
if(error) {
error->parser_code = (long)err_code;
error->line = line_num;
error->column = col_num;
error->byte_index = byte_idx;
error->parser_error = error_str;
}
}
else {
xReturn = (xml_element*)Q_Head(&mydata.root->children);
xReturn->parent = NULL;
}
XML_ParserFree(parser);
xml_elem_free_non_recurse(mydata.root);
}
return xReturn;
}
|
CWE-125
| 1
|
1
|
int __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc)
{
xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc;
__GLXconfig *config;
__GLXscreen *pGlxScreen;
int err;
if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err))
return err;
if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err))
config, pGlxScreen, req->isDirect);
}
|
CWE-20
| 2
|
0
|
int ssl3_peek(SSL *s, void *buf, int len)
{
return ssl3_read_internal(s, buf, len, 1);
}
|
none
| 8
|
1
|
static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
X509_ALGOR **pmaskHash)
{
const unsigned char *p;
int plen;
RSA_PSS_PARAMS *pss;
*pmaskHash = NULL;
if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen);
if (!pss)
return NULL;
if (pss->maskGenAlgorithm) {
ASN1_TYPE *param = pss->maskGenAlgorithm->parameter;
if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1
&& param->type == V_ASN1_SEQUENCE) {
p = param->value.sequence->data;
plen = param->value.sequence->length;
*pmaskHash = d2i_X509_ALGOR(NULL, &p, plen);
}
}
return pss;
}
|
CWE-476
| 6
|
1
|
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper,
const char *path, const char *mode, int options, char **opened_path,
php_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */
{
php_stream *stream = NULL;
php_url *resource = NULL;
int use_ssl;
int use_proxy = 0;
char *scratch = NULL;
char *tmp = NULL;
char *ua_str = NULL;
zval **ua_zval = NULL, **tmpzval = NULL, *ssl_proxy_peer_name = NULL;
int scratch_len = 0;
int body = 0;
char location[HTTP_HEADER_BLOCK_SIZE];
zval *response_header = NULL;
int reqok = 0;
char *http_header_line = NULL;
char tmp_line[128];
size_t chunk_size = 0, file_size = 0;
int eol_detect = 0;
char *transport_string, *errstr = NULL;
int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0;
char *protocol_version = NULL;
int protocol_version_len = 3; /* Default: "1.0" */
struct timeval timeout;
char *user_headers = NULL;
int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0);
int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0);
int follow_location = 1;
php_stream_filter *transfer_encoding = NULL;
int response_code;
tmp_line[0] = '\0';
if (redirect_max < 1) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting");
return NULL;
}
resource = php_url_parse(path);
if (resource == NULL) {
return NULL;
}
if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) {
if (!context ||
php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE ||
Z_TYPE_PP(tmpzval) != IS_STRING ||
Z_STRLEN_PP(tmpzval) <= 0) {
php_url_free(resource);
return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context);
}
/* Called from a non-http wrapper with http proxying requested (i.e. ftp) */
request_fulluri = 1;
use_ssl = 0;
use_proxy = 1;
transport_len = Z_STRLEN_PP(tmpzval);
transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
} else {
/* Normal http request (possibly with proxy) */
if (strpbrk(mode, "awx+")) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections");
php_url_free(resource);
return NULL;
}
use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's';
/* choose default ports */
if (use_ssl && resource->port == 0)
resource->port = 443;
else if (resource->port == 0)
resource->port = 80;
if (context &&
php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS &&
Z_TYPE_PP(tmpzval) == IS_STRING &&
Z_STRLEN_PP(tmpzval) > 0) {
use_proxy = 1;
transport_len = Z_STRLEN_PP(tmpzval);
transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
} else {
transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port);
}
}
if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_double_ex(tmpzval);
timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval);
timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000);
} else {
timeout.tv_sec = FG(default_socket_timeout);
timeout.tv_usec = 0;
}
stream = php_stream_xport_create(transport_string, transport_len, options,
STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT,
NULL, &timeout, context, &errstr, NULL);
if (stream) {
php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout);
}
if (errstr) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr);
efree(errstr);
errstr = NULL;
}
efree(transport_string);
if (stream && use_proxy && use_ssl) {
smart_str header = {0};
/* Set peer_name or name verification will try to use the proxy server name */
if (!context || php_stream_context_get_option(context, "ssl", "peer_name", &tmpzval) == FAILURE) {
MAKE_STD_ZVAL(ssl_proxy_peer_name);
ZVAL_STRING(ssl_proxy_peer_name, resource->host, 1);
php_stream_context_set_option(stream->context, "ssl", "peer_name", ssl_proxy_peer_name);
}
smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1);
smart_str_appends(&header, resource->host);
smart_str_appendc(&header, ':');
smart_str_append_unsigned(&header, resource->port);
smart_str_appendl(&header, " HTTP/1.0\r\n", sizeof(" HTTP/1.0\r\n")-1);
/* check if we have Proxy-Authorization header */
if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) {
char *s, *p;
if (Z_TYPE_PP(tmpzval) == IS_ARRAY) {
HashPosition pos;
zval **tmpheader = NULL;
for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos);
SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos);
zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)) {
if (Z_TYPE_PP(tmpheader) == IS_STRING) {
s = Z_STRVAL_PP(tmpheader);
do {
while (*s == ' ' || *s == '\t') s++;
p = s;
while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++;
if (*p == ':') {
p++;
if (p - s == sizeof("Proxy-Authorization:") - 1 &&
zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1,
"Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
smart_str_appendl(&header, s, p - s);
smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
goto finish;
} else {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
}
}
s = p;
while (*s == '\r' || *s == '\n') s++;
} while (*s != 0);
}
}
} else if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) {
s = Z_STRVAL_PP(tmpzval);
do {
while (*s == ' ' || *s == '\t') s++;
p = s;
while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++;
if (*p == ':') {
p++;
if (p - s == sizeof("Proxy-Authorization:") - 1 &&
zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1,
"Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
smart_str_appendl(&header, s, p - s);
smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
goto finish;
} else {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
}
}
s = p;
while (*s == '\r' || *s == '\n') s++;
} while (*s != 0);
}
}
finish:
smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
if (php_stream_write(stream, header.c, header.len) != header.len) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy");
php_stream_close(stream);
stream = NULL;
}
smart_str_free(&header);
if (stream) {
char header_line[HTTP_HEADER_BLOCK_SIZE];
/* get response header */
while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) {
if (header_line[0] == '\n' ||
header_line[0] == '\r' ||
header_line[0] == '\0') {
break;
}
}
}
/* enable SSL transport layer */
if (stream) {
if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 ||
php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy");
php_stream_close(stream);
stream = NULL;
}
}
}
if (stream == NULL)
goto out;
/* avoid buffering issues while reading header */
if (options & STREAM_WILL_CAST)
chunk_size = php_stream_set_chunk_size(stream, 1);
/* avoid problems with auto-detecting when reading the headers -> the headers
* are always in canonical \r\n format */
eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
php_stream_context_set(stream, context);
php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0);
if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_long_ex(tmpzval);
redirect_max = Z_LVAL_PP(tmpzval);
}
if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) {
if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
/* As per the RFC, automatically redirected requests MUST NOT use other methods than
* GET and HEAD unless it can be confirmed by the user */
if (!redirected
|| (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0)
|| (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0)
) {
scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval);
scratch = emalloc(scratch_len);
strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1);
strncat(scratch, " ", 1);
}
}
}
if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_double_ex(tmpzval);
protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval));
}
if (!scratch) {
scratch_len = strlen(path) + 29 + protocol_version_len;
scratch = emalloc(scratch_len);
strncpy(scratch, "GET ", scratch_len);
}
/* Should we send the entire path in the request line, default to no. */
if (!request_fulluri &&
context &&
php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) {
zval ztmp = **tmpzval;
zval_copy_ctor(&ztmp);
convert_to_boolean(&ztmp);
request_fulluri = Z_BVAL(ztmp) ? 1 : 0;
zval_dtor(&ztmp);
}
if (request_fulluri) {
/* Ask for everything */
strcat(scratch, path);
} else {
/* Send the traditional /path/to/file?query_string */
/* file */
if (resource->path && *resource->path) {
strlcat(scratch, resource->path, scratch_len);
} else {
strlcat(scratch, "/", scratch_len);
}
/* query string */
if (resource->query) {
strlcat(scratch, "?", scratch_len);
strlcat(scratch, resource->query, scratch_len);
}
}
/* protocol version we are speaking */
if (protocol_version) {
strlcat(scratch, " HTTP/", scratch_len);
strlcat(scratch, protocol_version, scratch_len);
strlcat(scratch, "\r\n", scratch_len);
} else {
strlcat(scratch, " HTTP/1.0\r\n", scratch_len);
}
/* send it */
php_stream_write(stream, scratch, strlen(scratch));
if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) {
tmp = NULL;
if (Z_TYPE_PP(tmpzval) == IS_ARRAY) {
HashPosition pos;
zval **tmpheader = NULL;
smart_str tmpstr = {0};
for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos);
SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos);
zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)
) {
if (Z_TYPE_PP(tmpheader) == IS_STRING) {
smart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader));
smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1);
}
}
smart_str_0(&tmpstr);
/* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */
if (tmpstr.c) {
tmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC);
smart_str_free(&tmpstr);
}
}
if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) {
/* Remove newlines and spaces from start and end php_trim will estrndup() */
tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC);
}
if (tmp && strlen(tmp) > 0) {
char *s;
user_headers = estrdup(tmp);
/* Make lowercase for easy comparison against 'standard' headers */
php_strtolower(tmp, strlen(tmp));
if (!header_init) {
/* strip POST headers on redirect */
strip_header(user_headers, tmp, "content-length:");
strip_header(user_headers, tmp, "content-type:");
}
if ((s = strstr(tmp, "user-agent:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_USER_AGENT;
}
if ((s = strstr(tmp, "host:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_HOST;
}
if ((s = strstr(tmp, "from:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_FROM;
}
if ((s = strstr(tmp, "authorization:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_AUTH;
}
if ((s = strstr(tmp, "content-length:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_CONTENT_LENGTH;
}
if ((s = strstr(tmp, "content-type:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_TYPE;
}
if ((s = strstr(tmp, "connection:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_CONNECTION;
}
/* remove Proxy-Authorization header */
if (use_proxy && use_ssl && (s = strstr(tmp, "proxy-authorization:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
char *p = s + sizeof("proxy-authorization:") - 1;
while (s > tmp && (*(s-1) == ' ' || *(s-1) == '\t')) s--;
while (*p != 0 && *p != '\r' && *p != '\n') p++;
while (*p == '\r' || *p == '\n') p++;
if (*p == 0) {
if (s == tmp) {
efree(user_headers);
user_headers = NULL;
} else {
while (s > tmp && (*(s-1) == '\r' || *(s-1) == '\n')) s--;
user_headers[s - tmp] = 0;
}
} else {
memmove(user_headers + (s - tmp), user_headers + (p - tmp), strlen(p) + 1);
}
}
}
if (tmp) {
efree(tmp);
}
}
/* auth header if it was specified */
if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) {
/* decode the strings first */
php_url_decode(resource->user, strlen(resource->user));
/* scratch is large enough, since it was made large enough for the whole URL */
strcpy(scratch, resource->user);
strcat(scratch, ":");
/* Note: password is optional! */
if (resource->pass) {
php_url_decode(resource->pass, strlen(resource->pass));
strcat(scratch, resource->pass);
}
tmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL);
if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) {
php_stream_write(stream, scratch, strlen(scratch));
php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0);
}
efree(tmp);
tmp = NULL;
}
/* if the user has configured who they are, send a From: line */
if (((have_header & HTTP_HEADER_FROM) == 0) && FG(from_address)) {
if (snprintf(scratch, scratch_len, "From: %s\r\n", FG(from_address)) > 0)
php_stream_write(stream, scratch, strlen(scratch));
}
/* Send Host: header so name-based virtual hosts work */
if ((have_header & HTTP_HEADER_HOST) == 0) {
if ((use_ssl && resource->port != 443 && resource->port != 0) ||
(!use_ssl && resource->port != 80 && resource->port != 0)) {
if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0)
php_stream_write(stream, scratch, strlen(scratch));
} else {
if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) {
php_stream_write(stream, scratch, strlen(scratch));
}
}
}
/* Send a Connection: close header to avoid hanging when the server
* interprets the RFC literally and establishes a keep-alive connection,
* unless the user specifically requests something else by specifying a
* Connection header in the context options. Send that header even for
* HTTP/1.0 to avoid issues when the server respond with a HTTP/1.1
* keep-alive response, which is the preferred response type. */
if ((have_header & HTTP_HEADER_CONNECTION) == 0) {
php_stream_write_string(stream, "Connection: close\r\n");
}
if (context &&
php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS &&
Z_TYPE_PP(ua_zval) == IS_STRING) {
ua_str = Z_STRVAL_PP(ua_zval);
} else if (FG(user_agent)) {
ua_str = FG(user_agent);
}
if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) {
#define _UA_HEADER "User-Agent: %s\r\n"
char *ua;
size_t ua_len;
ua_len = sizeof(_UA_HEADER) + strlen(ua_str);
/* ensure the header is only sent if user_agent is not blank */
if (ua_len > sizeof(_UA_HEADER)) {
ua = emalloc(ua_len + 1);
if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) {
ua[ua_len] = 0;
php_stream_write(stream, ua, ua_len);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header");
}
if (ua) {
efree(ua);
}
}
}
if (user_headers) {
/* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST
* see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first.
*/
if (
header_init &&
context &&
!(have_header & HTTP_HEADER_CONTENT_LENGTH) &&
php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0
) {
scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval));
php_stream_write(stream, scratch, scratch_len);
have_header |= HTTP_HEADER_CONTENT_LENGTH;
}
php_stream_write(stream, user_headers, strlen(user_headers));
php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
efree(user_headers);
}
/* Request content, such as for POST requests */
if (header_init && context &&
php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) {
scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval));
php_stream_write(stream, scratch, scratch_len);
}
if (!(have_header & HTTP_HEADER_TYPE)) {
php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n",
sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1);
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded");
}
php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
} else {
php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
}
location[0] = '\0';
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
if (header_init) {
zval *ztmp;
MAKE_STD_ZVAL(ztmp);
array_init(ztmp);
ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", ztmp);
}
{
zval **rh;
if(zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh) != SUCCESS || Z_TYPE_PP(rh) != IS_ARRAY) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, http_response_header overwritten");
goto out;
}
response_header = *rh;
Z_ADDREF_P(response_header);
}
if (!php_stream_eof(stream)) {
size_t tmp_line_len;
/* get response header */
if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) {
zval *http_response;
if (tmp_line_len > 9) {
response_code = atoi(tmp_line + 9);
} else {
response_code = 0;
}
if (context && SUCCESS==php_stream_context_get_option(context, "http", "ignore_errors", &tmpzval)) {
ignore_errors = zend_is_true(*tmpzval);
}
/* when we request only the header, don't fail even on error codes */
if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) {
reqok = 1;
}
/* status codes of 1xx are "informational", and will be followed by a real response
* e.g "100 Continue". RFC 7231 states that unexpected 1xx status MUST be parsed,
* and MAY be ignored. As such, we need to skip ahead to the "real" status*/
if (response_code >= 100 && response_code < 200) {
/* consume lines until we find a line starting 'HTTP/1' */
while (
!php_stream_eof(stream)
&& php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL
&& ( tmp_line_len < sizeof("HTTP/1") - 1 || strncasecmp(tmp_line, "HTTP/1", sizeof("HTTP/1") - 1) )
);
if (tmp_line_len > 9) {
response_code = atoi(tmp_line + 9);
} else {
response_code = 0;
}
}
/* all status codes in the 2xx range are defined by the specification as successful;
* all status codes in the 3xx range are for redirection, and so also should never
* fail */
if (response_code >= 200 && response_code < 400) {
reqok = 1;
} else {
switch(response_code) {
case 403:
php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT,
tmp_line, response_code);
break;
default:
/* safety net in the event tmp_line == NULL */
if (!tmp_line_len) {
tmp_line[0] = '\0';
}
php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE,
tmp_line, response_code);
}
}
if (tmp_line[tmp_line_len - 1] == '\n') {
--tmp_line_len;
if (tmp_line[tmp_line_len - 1] == '\r') {
--tmp_line_len;
}
}
MAKE_STD_ZVAL(http_response);
ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1);
zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL);
}
} else {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!");
goto out;
}
/* read past HTTP headers */
http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE);
while (!body && !php_stream_eof(stream)) {
size_t http_header_line_length;
if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') {
char *e = http_header_line + http_header_line_length - 1;
if (*e != '\n') {
do { /* partial header */
if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) == NULL) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Failed to read HTTP headers");
goto out;
}
e = http_header_line + http_header_line_length - 1;
} while (*e != '\n');
continue;
}
while (*e == '\n' || *e == '\r') {
e--;
}
http_header_line_length = e - http_header_line + 1;
http_header_line[http_header_line_length] = '\0';
if (!strncasecmp(http_header_line, "Location: ", 10)) {
if (context && php_stream_context_get_option(context, "http", "follow_location", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_long_ex(tmpzval);
follow_location = Z_LVAL_PP(tmpzval);
} else if (!(response_code >= 300 && response_code < 304 || 307 == response_code || 308 == response_code)) {
/* we shouldn't redirect automatically
if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307)
see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1
RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */
follow_location = 0;
}
strlcpy(location, http_header_line + 10, sizeof(location));
} else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) {
php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0);
} else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) {
file_size = atoi(http_header_line + 16);
php_stream_notify_file_size(context, file_size, http_header_line, 0);
} else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) {
/* create filter to decode response body */
if (!(options & STREAM_ONLY_GET_HEADERS)) {
long decode = 1;
if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_boolean(*tmpzval);
decode = Z_LVAL_PP(tmpzval);
}
if (decode) {
transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC);
if (transfer_encoding) {
/* don't store transfer-encodeing header */
continue;
}
}
}
}
if (http_header_line[0] == '\0') {
body = 1;
} else {
zval *http_header;
MAKE_STD_ZVAL(http_header);
ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1);
zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL);
}
} else {
break;
}
}
if (!reqok || (location[0] != '\0' && follow_location)) {
if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) {
goto out;
}
if (location[0] != '\0')
php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0);
php_stream_close(stream);
stream = NULL;
if (location[0] != '\0') {
char new_path[HTTP_HEADER_BLOCK_SIZE];
char loc_path[HTTP_HEADER_BLOCK_SIZE];
*new_path='\0';
if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) &&
strncasecmp(location, "https://", sizeof("https://")-1) &&
strncasecmp(location, "ftp://", sizeof("ftp://")-1) &&
strncasecmp(location, "ftps://", sizeof("ftps://")-1)))
{
if (*location != '/') {
if (*(location+1) != '\0' && resource->path) {
char *s = strrchr(resource->path, '/');
if (!s) {
s = resource->path;
if (!s[0]) {
efree(s);
s = resource->path = estrdup("/");
} else {
*s = '/';
}
}
s[1] = '\0';
if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') {
snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location);
} else {
snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location);
}
} else {
snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location);
}
} else {
strlcpy(loc_path, location, sizeof(loc_path));
}
if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) {
snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path);
} else {
snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path);
}
} else {
strlcpy(new_path, location, sizeof(new_path));
}
php_url_free(resource);
/* check for invalid redirection URLs */
if ((resource = php_url_parse(new_path)) == NULL) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path);
goto out;
}
#define CHECK_FOR_CNTRL_CHARS(val) { \
if (val) { \
unsigned char *s, *e; \
int l; \
l = php_url_decode(val, strlen(val)); \
s = (unsigned char*)val; e = s + l; \
while (s < e) { \
if (iscntrl(*s)) { \
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \
goto out; \
} \
s++; \
} \
} \
}
/* check for control characters in login, password & path */
if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) {
CHECK_FOR_CNTRL_CHARS(resource->user)
CHECK_FOR_CNTRL_CHARS(resource->pass)
CHECK_FOR_CNTRL_CHARS(resource->path)
}
stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC);
} else {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed! %s", tmp_line);
}
}
out:
if (protocol_version) {
efree(protocol_version);
}
if (http_header_line) {
efree(http_header_line);
}
if (scratch) {
efree(scratch);
}
if (resource) {
php_url_free(resource);
}
if (stream) {
if (header_init) {
stream->wrapperdata = response_header;
} else {
if(response_header) {
Z_DELREF_P(response_header);
}
}
php_stream_notify_progress_init(context, 0, file_size);
/* Restore original chunk size now that we're done with headers */
if (options & STREAM_WILL_CAST)
php_stream_set_chunk_size(stream, chunk_size);
/* restore the users auto-detect-line-endings setting */
stream->flags |= eol_detect;
/* as far as streams are concerned, we are now at the start of
* the stream */
stream->position = 0;
/* restore mode */
strlcpy(stream->mode, mode, sizeof(stream->mode));
if (transfer_encoding) {
php_stream_filter_append(&stream->readfilters, transfer_encoding);
}
} else {
if(response_header) {
Z_DELREF_P(response_header);
}
if (transfer_encoding) {
php_stream_filter_free(transfer_encoding TSRMLS_CC);
}
}
return stream;
}
|
CWE-119
| 0
|
0
|
int parse_checksum_choice(void)
{
char *cp = checksum_choice ? strchr(checksum_choice, ',') : NULL;
if (cp) {
xfersum_type = parse_csum_name(checksum_choice, cp - checksum_choice);
checksum_type = parse_csum_name(cp+1, -1);
} else
xfersum_type = checksum_type = parse_csum_name(checksum_choice, -1);
return xfersum_type == CSUM_NONE;
}
|
none
| 8
|
1
|
PHP_FUNCTION(imagetruecolortopalette)
{
zval *IM;
zend_bool dither;
zend_long ncolors;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rbl", &IM, &dither, &ncolors) == FAILURE) {
return;
}
if ((im = (gdImagePtr)zend_fetch_resource(Z_RES_P(IM), "Image", le_gd)) == NULL) {
RETURN_FALSE;
}
if (ncolors <= 0) {
php_error_docref(NULL, E_WARNING, "Number of colors has to be greater than zero");
RETURN_FALSE;
}
gdImageTrueColorToPalette(im, dither, ncolors);
RETURN_TRUE;
}
|
CWE-787
| 7
|
1
|
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
{
const char
*option;
Image
*image;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
opj_codestream_index_t
*codestream_index = (opj_codestream_index_t *) NULL;
opj_dparameters_t
parameters;
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned char
sans[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JP2 codec.
*/
if (ReadBlob(image,4,sans) != 4)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SeekBlob(image,SEEK_SET,0);
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
else
if (IsJ2K(sans,4) != MagickFalse)
jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
opj_set_default_decoder_parameters(¶meters);
option=GetImageOption(image_info,"jp2:reduce-factor");
if (option != (const char *) NULL)
parameters.cp_reduce=StringToInteger(option);
option=GetImageOption(image_info,"jp2:quality-layers");
if (option == (const char *) NULL)
option=GetImageOption(image_info,"jp2:layer-number");
if (option != (const char *) NULL)
parameters.cp_layer=StringToInteger(option);
if (opj_setup_decoder(jp2_codec,¶meters) == 0)
{
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
}
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
jp2_status=1;
if ((image->columns != 0) && (image->rows != 0))
{
/*
Extract an area from the image.
*/
jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
(OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
(OPJ_INT32) image->extract_info.x+(ssize_t) image->columns,
(OPJ_INT32) image->extract_info.y+(ssize_t) image->rows);
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
}
if ((image_info->number_scenes != 0) && (image_info->scene != 0))
jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
(unsigned int) image_info->scene-1);
else
if (image->ping == MagickFalse)
{
jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
if (jp2_status != 0)
jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
}
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
opj_stream_destroy(jp2_stream);
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) ||
(jp2_image->comps[0].dx != jp2_image->comps[i].dx) ||
(jp2_image->comps[0].dy != jp2_image->comps[i].dy) ||
(jp2_image->comps[0].prec != jp2_image->comps[i].prec) ||
(jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd))
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
}
}
/*
Convert JP2 image.
*/
image->columns=(size_t) jp2_image->comps[0].w;
image->rows=(size_t) jp2_image->comps[0].h;
image->depth=jp2_image->comps[0].prec;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->compression=JPEG2000Compression;
if (jp2_image->color_space == 2)
{
SetImageColorspace(image,GRAYColorspace);
if (jp2_image->numcomps > 1)
image->matte=MagickTrue;
}
else
if (jp2_image->color_space == 3)
SetImageColorspace(image,Rec601YCbCrColorspace);
if (jp2_image->numcomps > 3)
image->matte=MagickTrue;
if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
{
StringInfo
*profile;
profile=BlobToStringInfo(jp2_image->icc_profile_buf,
jp2_image->icc_profile_len);
if (profile != (StringInfo *) NULL)
SetImageProfile(image,"icc",profile);
}
if (image->ping != MagickFalse)
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
return(GetFirstImageInList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
double
pixel,
scale;
scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
(jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
switch (i)
{
case 0:
{
q->red=ClampToQuantum(pixel);
q->green=q->red;
q->blue=q->red;
q->opacity=OpaqueOpacity;
break;
}
case 1:
{
if (jp2_image->numcomps == 2)
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
q->green=ClampToQuantum(pixel);
break;
}
case 2:
{
q->blue=ClampToQuantum(pixel);
break;
}
case 3:
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free resources.
*/
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
|
CWE-20
| 2
|
1
|
bool HTMLFormControlElement::isAutofocusable() const
{
if (!fastHasAttribute(autofocusAttr))
return false;
if (hasTagName(inputTag))
return !toHTMLInputElement(this)->isInputTypeHidden();
if (hasTagName(selectTag))
return true;
if (hasTagName(keygenTag))
return true;
if (hasTagName(buttonTag))
return true;
if (hasTagName(textareaTag))
return true;
return false;
}
|
CWE-119
| 0
|
1
|
xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){
xmlNodePtr cur = NULL;
long val;
xmlChar str[30];
xmlDocPtr doc;
if (nargs == 0) {
cur = ctxt->context->node;
} else if (nargs == 1) {
xmlXPathObjectPtr obj;
xmlNodeSetPtr nodelist;
int i, ret;
if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) {
ctxt->error = XPATH_INVALID_TYPE;
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"generate-id() : invalid arg expecting a node-set\n");
return;
}
obj = valuePop(ctxt);
nodelist = obj->nodesetval;
if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) {
xmlXPathFreeObject(obj);
valuePush(ctxt, xmlXPathNewCString(""));
return;
}
cur = nodelist->nodeTab[0];
for (i = 1;i < nodelist->nodeNr;i++) {
ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]);
if (ret == -1)
cur = nodelist->nodeTab[i];
}
xmlXPathFreeObject(obj);
} else {
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"generate-id() : invalid number of args %d\n", nargs);
ctxt->error = XPATH_INVALID_ARITY;
return;
}
/*
* Okay this is ugly but should work, use the NodePtr address
* to forge the ID
*/
if (cur->type != XML_NAMESPACE_DECL)
doc = cur->doc;
else {
xmlNsPtr ns = (xmlNsPtr) cur;
if (ns->context != NULL)
doc = ns->context;
else
doc = ctxt->context->doc;
}
val = (long)((char *)cur - (char *)doc);
if (val >= 0) {
sprintf((char *)str, "idp%ld", val);
} else {
sprintf((char *)str, "idm%ld", -val);
}
valuePush(ctxt, xmlXPathNewString(str));
}
|
CWE-399
| 4
|
0
|
pdf_drop_cmap(fz_context *ctx, pdf_cmap *cmap)
{
fz_drop_storable(ctx, &cmap->storable);
}
|
none
| 8
|
0
|
poppler_page_free_annot_mapping (GList *list)
{
if (!list)
return;
g_list_foreach (list, (GFunc)poppler_annot_mapping_free, NULL);
g_list_free (list);
}
|
none
| 8
|
0
|
static SpiceCharDeviceMsgToClient *vdi_port_read_one_msg_from_device(SpiceCharDeviceInstance *sin,
void *opaque)
{
VDIPortState *state = &reds->agent_state;
SpiceCharDeviceInterface *sif;
VDIReadBuf *dispatch_buf;
int n;
if (!vdagent) {
return NULL;
}
spice_assert(vdagent == sin);
sif = SPICE_CONTAINEROF(vdagent->base.sif, SpiceCharDeviceInterface, base);
while (vdagent) {
switch (state->read_state) {
case VDI_PORT_READ_STATE_READ_HEADER:
n = sif->read(vdagent, state->receive_pos, state->receive_len);
if (!n) {
return NULL;
}
if ((state->receive_len -= n)) {
state->receive_pos += n;
return NULL;
}
state->message_receive_len = state->vdi_chunk_header.size;
state->read_state = VDI_PORT_READ_STATE_GET_BUFF;
case VDI_PORT_READ_STATE_GET_BUFF: {
if (!(state->current_read_buf = vdi_port_read_buf_get())) {
return NULL;
}
state->receive_pos = state->current_read_buf->data;
state->receive_len = MIN(state->message_receive_len,
sizeof(state->current_read_buf->data));
state->current_read_buf->len = state->receive_len;
state->message_receive_len -= state->receive_len;
state->read_state = VDI_PORT_READ_STATE_READ_DATA;
}
case VDI_PORT_READ_STATE_READ_DATA:
n = sif->read(vdagent, state->receive_pos, state->receive_len);
if (!n) {
return NULL;
}
if ((state->receive_len -= n)) {
state->receive_pos += n;
break;
}
dispatch_buf = state->current_read_buf;
state->current_read_buf = NULL;
state->receive_pos = NULL;
if (state->message_receive_len == 0) {
state->read_state = VDI_PORT_READ_STATE_READ_HEADER;
state->receive_pos = (uint8_t *)&state->vdi_chunk_header;
state->receive_len = sizeof(state->vdi_chunk_header);
} else {
state->read_state = VDI_PORT_READ_STATE_GET_BUFF;
}
if (vdi_port_read_buf_process(state->vdi_chunk_header.port, dispatch_buf)) {
return dispatch_buf;
} else {
vdi_port_read_buf_unref(dispatch_buf);
}
} /* END switch */
} /* END while */
return NULL;
}
|
none
| 8
|
1
|
static int rose_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct full_sockaddr_rose *srose = (struct full_sockaddr_rose *)uaddr;
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
int n;
if (peer != 0) {
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
srose->srose_family = AF_ROSE;
srose->srose_addr = rose->dest_addr;
srose->srose_call = rose->dest_call;
srose->srose_ndigis = rose->dest_ndigis;
for (n = 0; n < rose->dest_ndigis; n++)
srose->srose_digis[n] = rose->dest_digis[n];
} else {
srose->srose_family = AF_ROSE;
srose->srose_addr = rose->source_addr;
srose->srose_call = rose->source_call;
srose->srose_ndigis = rose->source_ndigis;
for (n = 0; n < rose->source_ndigis; n++)
srose->srose_digis[n] = rose->source_digis[n];
}
*uaddr_len = sizeof(struct full_sockaddr_rose);
return 0;
}
|
CWE-200
| 3
|
1
|
int ldb_handler_fold(struct ldb_context *ldb, void *mem_ctx,
const struct ldb_val *in, struct ldb_val *out)
{
char *s, *t;
size_t l;
if (!in || !out || !(in->data)) {
return -1;
}
out->data = (uint8_t *)ldb_casefold(ldb, mem_ctx, (const char *)(in->data), in->length);
if (out->data == NULL) {
ldb_debug(ldb, LDB_DEBUG_ERROR, "ldb_handler_fold: unable to casefold string [%.*s]", (int)in->length, (const char *)in->data);
return -1;
}
s = (char *)(out->data);
/* remove trailing spaces if any */
l = strlen(s);
while (l > 0 && s[l - 1] == ' ') l--;
s[l] = '\0';
/* remove leading spaces if any */
if (*s == ' ') {
for (t = s; *s == ' '; s++) ;
/* remove leading spaces by moving down the string */
memmove(t, s, l);
s = t;
}
/* check middle spaces */
while ((t = strchr(s, ' ')) != NULL) {
for (s = t; *s == ' '; s++) ;
if ((s - t) > 1) {
l = strlen(s);
/* remove all spaces but one by moving down the string */
memmove(t + 1, s, l);
}
}
out->length = strlen((char *)out->data);
return 0;
}
|
CWE-787
| 7
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- -