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 &param : 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(&parameters); 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,&parameters) == 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
0
static int reds_set_migration_dest_info(const char* dest, int port, int secure_port, const char* cert_subject) { RedsMigSpice *spice_migration = NULL; reds_mig_release(); if ((port == -1 && secure_port == -1) || !dest) { return FALSE; } spice_migration = spice_new0(RedsMigSpice, 1); spice_migration->port = port; spice_migration->sport = secure_port; spice_migration->host = spice_strdup(dest); if (cert_subject) { spice_migration->cert_subject = spice_strdup(cert_subject); } reds->mig_spice = spice_migration; return TRUE; }
none
8
1
static bool blit_is_unsafe(struct CirrusVGAState *s) { /* should be the case, see cirrus_bitblt_start */ assert(s->cirrus_blt_width > 0); assert(s->cirrus_blt_height > 0); if (blit_region_is_unsafe(s, s->cirrus_blt_dstpitch, s->cirrus_blt_dstaddr & s->cirrus_addr_mask)) { return true; } if (blit_region_is_unsafe(s, s->cirrus_blt_srcpitch, s->cirrus_blt_srcaddr & s->cirrus_addr_mask)) { return true; } return false; }
CWE-119
0
0
poppler_annot_mapping_new (void) { return (PopplerAnnotMapping *) g_new0 (PopplerAnnotMapping, 1); }
none
8
1
static int mb86a20s_read_status(struct dvb_frontend *fe, enum fe_status *status) { struct mb86a20s_state *state = fe->demodulator_priv; int val; *status = 0; val = mb86a20s_readreg(state, 0x0a) & 0xf; if (val < 0) return val; if (val >= 2) *status |= FE_HAS_SIGNAL; if (val >= 4) *status |= FE_HAS_CARRIER; if (val >= 5) *status |= FE_HAS_VITERBI; if (val >= 7) *status |= FE_HAS_SYNC; if (val >= 8) /* Maybe 9? */ *status |= FE_HAS_LOCK; dev_dbg(&state->i2c->dev, "%s: Status = 0x%02x (state = %d)\n", __func__, *status, val); return val; }
CWE-119
0
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 blocklist is copied from linux-user-chroot, which was in turn * clearly influenced by the Sandstorm.io blocklist. * * 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/#!forum/libseccomp * * A non-exhaustive list of links to container tooling that might * want to share this blocklist: * * 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 * * Other useful resources: * https://github.com/systemd/systemd/blob/HEAD/src/shared/seccomp-util.c * https://github.com/moby/moby/blob/HEAD/profiles/seccomp/default.json * **** END NOTE ON CODE SHARING */ struct { int scall; int errnum; struct scmp_arg_cmp *arg; } syscall_blocklist[] = { /* Block dmesg */ {SCMP_SYS (syslog), EPERM}, /* Useless old syscall */ {SCMP_SYS (uselib), EPERM}, /* Don't allow disabling accounting */ {SCMP_SYS (acct), EPERM}, /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a historic source of interesting information leaks. */ {SCMP_SYS (modify_ldt), EPERM}, /* Don't allow reading current quota use */ {SCMP_SYS (quotactl), EPERM}, /* Don't allow access to the kernel keyring */ {SCMP_SYS (add_key), EPERM}, {SCMP_SYS (keyctl), EPERM}, {SCMP_SYS (request_key), EPERM}, /* Scary VM/NUMA ops */ {SCMP_SYS (move_pages), EPERM}, {SCMP_SYS (mbind), EPERM}, {SCMP_SYS (get_mempolicy), EPERM}, {SCMP_SYS (set_mempolicy), EPERM}, {SCMP_SYS (migrate_pages), EPERM}, /* Don't allow subnamespace setups: */ {SCMP_SYS (unshare), EPERM}, {SCMP_SYS (setns), EPERM}, {SCMP_SYS (mount), EPERM}, {SCMP_SYS (pivot_root), EPERM}, #if defined(__s390__) || defined(__s390x__) || defined(__CRIS__) /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack * and flags arguments are reversed so the flags come second */ {SCMP_SYS (clone), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #else /* Normally the flags come first */ {SCMP_SYS (clone), EPERM, &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #endif /* Don't allow faking input to the controlling tty (CVE-2017-5226) */ {SCMP_SYS (ioctl), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)}, /* seccomp can't look into clone3()'s struct clone_args to check whether * the flags are OK, so we have no choice but to block clone3(). * Return ENOSYS so user-space will fall back to clone(). * (GHSA-67h7-w3jq-vh4q; see also https://github.com/moby/moby/commit/9f6b562d) */ {SCMP_SYS (clone3), ENOSYS}, /* New mount manipulation APIs can also change our VFS. There's no * legitimate reason to do these in the sandbox, so block all of them * rather than thinking about which ones might be dangerous. * (GHSA-67h7-w3jq-vh4q) */ {SCMP_SYS (open_tree), ENOSYS}, {SCMP_SYS (move_mount), ENOSYS}, {SCMP_SYS (fsopen), ENOSYS}, {SCMP_SYS (fsconfig), ENOSYS}, {SCMP_SYS (fsmount), ENOSYS}, {SCMP_SYS (fspick), ENOSYS}, {SCMP_SYS (mount_setattr), ENOSYS}, }; struct { int scall; int errnum; struct scmp_arg_cmp *arg; } syscall_nondevel_blocklist[] = { /* 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), EPERM}, /* Don't allow you to switch to bsd emulation or whatnot */ {SCMP_SYS (personality), EPERM, &SCMP_A0 (SCMP_CMP_NE, allowed_personality)}, {SCMP_SYS (ptrace), EPERM} }; /* Blocklist all but unix, inet, inet6 and netlink */ struct { int family; FlatpakRunFlags flags_mask; } socket_family_allowlist[] = { /* 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) { 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_blocklist); i++) { int scall = syscall_blocklist[i].scall; int errnum = syscall_blocklist[i].errnum; g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE); if (syscall_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), 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_blocklist); i++) { int scall = syscall_nondevel_blocklist[i].scall; int errnum = syscall_nondevel_blocklist[i].errnum; g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE); if (syscall_nondevel_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_nondevel_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), 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_allowlist); i++) { int family = socket_family_allowlist[i].family; int disallowed; if (socket_family_allowlist[i].flags_mask != 0 && (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask) continue; for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++) { /* Blocklist 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; } /* Blocklist 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_full (O_RDWR | O_CLOEXEC, "/tmp", &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
1
QPDF::read_xref(qpdf_offset_t xref_offset) { std::map<int, int> free_table; while (xref_offset) { char buf[7]; memset(buf, 0, sizeof(buf)); this->m->file->seek(xref_offset, SEEK_SET); this->m->file->read(buf, sizeof(buf) - 1); // The PDF spec says xref must be followed by a line // terminator, but files exist in the wild where it is // terminated by arbitrary whitespace. if ((strncmp(buf, "xref", 4) == 0) && QUtil::is_space(buf[4])) { QTC::TC("qpdf", "QPDF xref space", ((buf[4] == '\n') ? 0 : (buf[4] == '\r') ? 1 : (buf[4] == ' ') ? 2 : 9999)); int skip = 4; // buf is null-terminated, and QUtil::is_space('\0') is // false, so this won't overrun. while (QUtil::is_space(buf[skip])) { ++skip; } xref_offset = read_xrefTable(xref_offset + skip); } else { xref_offset = read_xrefStream(xref_offset); } } if (! this->m->trailer.isInitialized()) { throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, "unable to find trailer while reading xref"); } int size = this->m->trailer.getKey("/Size").getIntValue(); int max_obj = 0; if (! this->m->xref_table.empty()) { max_obj = (*(this->m->xref_table.rbegin())).first.getObj(); } if (! this->m->deleted_objects.empty()) { max_obj = std::max(max_obj, *(this->m->deleted_objects.rbegin())); } if (size != max_obj + 1) { QTC::TC("qpdf", "QPDF xref size mismatch"); warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, std::string("reported number of objects (") + QUtil::int_to_string(size) + ") inconsistent with actual number of objects (" + QUtil::int_to_string(max_obj + 1) + ")")); } // We no longer need the deleted_objects table, so go ahead and // clear it out to make sure we never depend on its being set. this->m->deleted_objects.clear(); }
CWE-399
4
1
int main(int argc, char *argv[]) { opj_dinfo_t* dinfo; opj_event_mgr_t event_mgr; /* event manager */ int tnum; unsigned int snum; opj_mj2_t *movie; mj2_tk_t *track; mj2_sample_t *sample; unsigned char* frame_codestream; FILE *file, *outfile; char outfilename[50]; mj2_dparameters_t parameters; if (argc != 3) { printf("Usage: %s mj2filename output_location\n", argv[0]); printf("Example: %s foreman.mj2 output/foreman\n", argv[0]); return 1; } file = fopen(argv[1], "rb"); if (!file) { fprintf(stderr, "failed to open %s for reading\n", argv[1]); return 1; } /* configure the event callbacks (not required) setting of each callback is optional */ memset(&event_mgr, 0, sizeof(opj_event_mgr_t)); event_mgr.error_handler = error_callback; event_mgr.warning_handler = warning_callback; event_mgr.info_handler = info_callback; /* get a MJ2 decompressor handle */ dinfo = mj2_create_decompress(); /* catch events using our callbacks and give a local context */ opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr); /* setup the decoder decoding parameters using user parameters */ memset(&parameters, 0, sizeof(mj2_dparameters_t)); movie = (opj_mj2_t*) dinfo->mj2_handle; mj2_setup_decoder(movie, &parameters); if (mj2_read_struct(file, movie)) { /* Creating the movie structure*/ return 1; } /* Decode first video track */ tnum = 0; while (movie->tk[tnum].track_type != 0) { tnum ++; } track = &movie->tk[tnum]; fprintf(stdout, "Extracting %d frames from file...\n", track->num_samples); for (snum = 0; snum < track->num_samples; snum++) { sample = &track->sample[snum]; frame_codestream = (unsigned char*) malloc(sample->sample_size - 8); /* Skipping JP2C marker*/ fseek(file, sample->offset + 8, SEEK_SET); fread(frame_codestream, sample->sample_size - 8, 1, file); /* Assuming that jp and ftyp markers size do*/ sprintf(outfilename, "%s_%05d.j2k", argv[2], snum); outfile = fopen(outfilename, "wb"); if (!outfile) { fprintf(stderr, "failed to open %s for writing\n", outfilename); return 1; } fwrite(frame_codestream, sample->sample_size - 8, 1, outfile); fclose(outfile); free(frame_codestream); } fclose(file); fprintf(stdout, "%d frames correctly extracted\n", snum); /* free remaining structures */ if (dinfo) { mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle); } return 0; }
CWE-119
0
0
static void nfs_set_fh(struct inode *inode, struct nfs_fh *fh) { struct nfs_inode *ninode = nfsi(inode); ninode->fh = *fh; }
none
8
1
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in) { int sx, sy; int i; int ncx, ncy, nc, cs, cx, cy; int x, y, ylo, yhi, xlo, xhi; int vers, fmt; t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */ unsigned char *chunkBuf = NULL; /* So we can gdFree it with impunity. */ int chunkNum = 0; int chunkMax = 0; uLongf chunkLen; int chunkPos = 0; int compMax = 0; int bytesPerPixel; char *compBuf = NULL; /* So we can gdFree it with impunity. */ gdImagePtr im; /* Get the header */ im = _gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx); if (im == NULL) { /* No need to free chunkIdx as _gd2CreateFromFile does it for us. */ return 0; } bytesPerPixel = im->trueColor ? 4 : 1; nc = ncx * ncy; if (gd2_compressed (fmt)) { /* Find the maximum compressed chunk size. */ compMax = 0; for (i = 0; (i < nc); i++) { if (chunkIdx[i].size > compMax) { compMax = chunkIdx[i].size; }; }; compMax++; /* Allocate buffers */ chunkMax = cs * bytesPerPixel * cs; chunkBuf = gdCalloc (chunkMax, 1); if (!chunkBuf) { goto fail; } compBuf = gdCalloc (compMax, 1); if (!compBuf) { goto fail; } GD2_DBG (printf ("Largest compressed chunk is %d bytes\n", compMax)); }; /* if ( (ncx != sx / cs) || (ncy != sy / cs)) { */ /* goto fail2; */ /* }; */ /* Read the data... */ for (cy = 0; (cy < ncy); cy++) { for (cx = 0; (cx < ncx); cx++) { ylo = cy * cs; yhi = ylo + cs; if (yhi > im->sy) { yhi = im->sy; }; GD2_DBG (printf ("Processing Chunk %d (%d, %d), y from %d to %d\n", chunkNum, cx, cy, ylo, yhi)); if (gd2_compressed (fmt)) { chunkLen = chunkMax; if (!_gd2ReadChunk (chunkIdx[chunkNum].offset, compBuf, chunkIdx[chunkNum].size, (char *) chunkBuf, &chunkLen, in)) { GD2_DBG (printf ("Error reading comproessed chunk\n")); goto fail; }; chunkPos = 0; }; for (y = ylo; (y < yhi); y++) { xlo = cx * cs; xhi = xlo + cs; if (xhi > im->sx) { xhi = im->sx; }; /*GD2_DBG(printf("y=%d: ",y)); */ if (!gd2_compressed (fmt)) { for (x = xlo; x < xhi; x++) { if (im->trueColor) { if (!gdGetInt (&im->tpixels[y][x], in)) { /*printf("EOF while reading\n"); */ /*gdImageDestroy(im); */ /*return 0; */ im->tpixels[y][x] = 0; } } else { int ch; if (!gdGetByte (&ch, in)) { /*printf("EOF while reading\n"); */ /*gdImageDestroy(im); */ /*return 0; */ ch = 0; } im->pixels[y][x] = ch; } } } else { for (x = xlo; x < xhi; x++) { if (im->trueColor) { /* 2.0.1: work around a gcc bug by being verbose. TBB */ int a = chunkBuf[chunkPos++] << 24; int r = chunkBuf[chunkPos++] << 16; int g = chunkBuf[chunkPos++] << 8; int b = chunkBuf[chunkPos++]; /* 2.0.11: tpixels */ im->tpixels[y][x] = a + r + g + b; } else { im->pixels[y][x] = chunkBuf[chunkPos++]; } }; }; /*GD2_DBG(printf("\n")); */ }; chunkNum++; }; }; GD2_DBG (printf ("Freeing memory\n")); gdFree (chunkBuf); gdFree (compBuf); gdFree (chunkIdx); GD2_DBG (printf ("Done\n")); return im; fail: gdImageDestroy (im); if (chunkBuf) { gdFree (chunkBuf); } if (compBuf) { gdFree (compBuf); } if (chunkIdx) { gdFree (chunkIdx); } return 0; }
CWE-20
2
1
static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg > regsz) { return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, &parameters_size); ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = "this"; debug_locals[argReg].descriptor = r_str_newf("%s;", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, &param_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf (" positions :\n"); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf (" 0x%04llx line=%llu\n", position->address, position->line); } rbin->cb_printf (" locals :\n"); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s " "%s\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s" "\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); }
CWE-476
6
0
GBool PSOutputDev::axialShadedFill(GfxState *state, GfxAxialShading *shading) { double xMin, yMin, xMax, yMax; double x0, y0, x1, y1, dx, dy, mul; double tMin, tMax, t, t0, t1; int i; if (level == psLevel2Sep || level == psLevel3Sep) { if (shading->getColorSpace()->getMode() != csDeviceCMYK) { return gFalse; } processColors |= psProcessCMYK; } state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax); shading->getCoords(&x0, &y0, &x1, &y1); dx = x1 - x0; dy = y1 - y0; if (fabs(dx) < 0.01 && fabs(dy) < 0.01) { return gTrue; } else { mul = 1 / (dx * dx + dy * dy); tMin = tMax = ((xMin - x0) * dx + (yMin - y0) * dy) * mul; t = ((xMin - x0) * dx + (yMax - y0) * dy) * mul; if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } t = ((xMax - x0) * dx + (yMin - y0) * dy) * mul; if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } t = ((xMax - x0) * dx + (yMax - y0) * dy) * mul; if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } if (tMin < 0 && !shading->getExtend0()) { tMin = 0; } if (tMax > 1 && !shading->getExtend1()) { tMax = 1; } } t0 = shading->getDomain0(); t1 = shading->getDomain1(); writePSFmt("/t0 {0:.4g} def\n", t0); writePSFmt("/t1 {0:.4g} def\n", t1); writePSFmt("/dt {0:.4g} def\n", t1 - t0); writePSFmt("/x0 {0:.4g} def\n", x0); writePSFmt("/y0 {0:.4g} def\n", y0); writePSFmt("/dx {0:.4g} def\n", x1 - x0); writePSFmt("/x1 {0:.4g} def\n", x1); writePSFmt("/y1 {0:.4g} def\n", y1); writePSFmt("/dy {0:.4g} def\n", y1 - y0); writePSFmt("/xMin {0:.4g} def\n", xMin); writePSFmt("/yMin {0:.4g} def\n", yMin); writePSFmt("/xMax {0:.4g} def\n", xMax); writePSFmt("/yMax {0:.4g} def\n", yMax); writePSFmt("/n {0:d} def\n", shading->getColorSpace()->getNComps()); if (shading->getNFuncs() == 1) { writePS("/func "); cvtFunction(shading->getFunc(0)); writePS("def\n"); } else { writePS("/func {\n"); for (i = 0; i < shading->getNFuncs(); ++i) { if (i < shading->getNFuncs() - 1) { writePS("dup\n"); } cvtFunction(shading->getFunc(i)); writePS("exec\n"); if (i < shading->getNFuncs() - 1) { writePS("exch\n"); } } writePS("} def\n"); } writePSFmt("{0:.4g} {1:.4g} 0 axialSH\n", tMin, tMax); return gTrue; }
none
8
1
static tmbstr ParseValue( TidyDocImpl* doc, ctmbstr name, Bool foldCase, Bool *isempty, int *pdelim) { Lexer* lexer = doc->lexer; int len = 0, start; Bool seen_gt = no; Bool munge = yes; uint c, lastc, delim, quotewarning; tmbstr value; delim = (tmbchar) 0; *pdelim = '"'; /* Henry Zrepa reports that some folk are using the embed element with script attributes where newlines are significant and must be preserved */ if ( cfgBool(doc, TidyLiteralAttribs) ) munge = no; /* skip white space before the '=' */ for (;;) { c = TY_(ReadChar)(doc->docIn); if (c == EndOfStream) { TY_(UngetChar)(c, doc->docIn); break; } if (!TY_(IsWhite)(c)) break; } /* c should be '=' if there is a value other legal possibilities are white space, '/' and '>' */ if (c != '=' && c != '"' && c != '\'') { TY_(UngetChar)(c, doc->docIn); return NULL; } /* skip white space after '=' */ for (;;) { c = TY_(ReadChar)(doc->docIn); if (c == EndOfStream) { TY_(UngetChar)(c, doc->docIn); break; } if (!TY_(IsWhite)(c)) break; } /* check for quote marks */ if (c == '"' || c == '\'') delim = c; else if (c == '<') { start = lexer->lexsize; TY_(AddCharToLexer)(lexer, c); *pdelim = ParseServerInstruction( doc ); len = lexer->lexsize - start; lexer->lexsize = start; return (len > 0 ? TY_(tmbstrndup)(doc->allocator, lexer->lexbuf+start, len) : NULL); } else TY_(UngetChar)(c, doc->docIn); /* and read the value string check for quote mark if needed */ quotewarning = 0; start = lexer->lexsize; c = '\0'; for (;;) { lastc = c; /* track last character */ c = TY_(ReadChar)(doc->docIn); if (c == EndOfStream) { TY_(ReportAttrError)( doc, lexer->token, NULL, UNEXPECTED_END_OF_FILE_ATTR ); TY_(UngetChar)(c, doc->docIn); break; } if (delim == (tmbchar)0) { if (c == '>') { TY_(UngetChar)(c, doc->docIn); break; } if (c == '"' || c == '\'') { uint q = c; TY_(ReportAttrError)( doc, lexer->token, NULL, UNEXPECTED_QUOTEMARK ); /* handle <input onclick=s("btn1")> and <a title=foo""">...</a> */ /* this doesn't handle <a title=foo"/> which browsers treat as */ /* 'foo"/' nor <a title=foo" /> which browser treat as 'foo"' */ c = TY_(ReadChar)(doc->docIn); if (c == '>') { TY_(AddCharToLexer)(lexer, q); TY_(UngetChar)(c, doc->docIn); break; } else { TY_(UngetChar)(c, doc->docIn); c = q; } } if (c == '<') { TY_(UngetChar)(c, doc->docIn); c = '>'; TY_(UngetChar)(c, doc->docIn); TY_(ReportAttrError)( doc, lexer->token, NULL, UNEXPECTED_GT ); break; } /* For cases like <br clear=all/> need to avoid treating /> as part of the attribute value, however care is needed to avoid so treating <a href=http://www.acme.com/> in this way, which would map the <a> tag to <a href="http://www.acme.com"/> */ if (c == '/') { /* peek ahead in case of /> */ c = TY_(ReadChar)(doc->docIn); if ( c == '>' && !TY_(IsUrl)(doc, name) ) { *isempty = yes; TY_(UngetChar)(c, doc->docIn); break; } /* unget peeked character */ TY_(UngetChar)(c, doc->docIn); c = '/'; } } else /* delim is '\'' or '"' */ { if (c == delim) break; if (c == '\n' || c == '<' || c == '>') ++quotewarning; if (c == '>') seen_gt = yes; } if (c == '&') { TY_(AddCharToLexer)(lexer, c); ParseEntity( doc, IgnoreWhitespace ); if (lexer->lexbuf[lexer->lexsize - 1] == '\n' && munge) ChangeChar(lexer, ' '); continue; } /* kludge for JavaScript attribute values with line continuations in string literals */ if (c == '\\') { c = TY_(ReadChar)(doc->docIn); if (c != '\n') { TY_(UngetChar)(c, doc->docIn); c = '\\'; } } if (TY_(IsWhite)(c)) { if ( delim == 0 ) break; if (munge) { /* discard line breaks in quoted URLs */ /* #438650 - fix by Randy Waki */ if ( c == '\n' && TY_(IsUrl)(doc, name) ) { /* warn that we discard this newline */ TY_(ReportAttrError)( doc, lexer->token, NULL, NEWLINE_IN_URI); continue; } c = ' '; if (lastc == ' ') { if (TY_(IsUrl)(doc, name) ) TY_(ReportAttrError)( doc, lexer->token, NULL, WHITE_IN_URI); continue; } } } else if (foldCase && TY_(IsUpper)(c)) c = TY_(ToLower)(c); TY_(AddCharToLexer)(lexer, c); } if (quotewarning > 10 && seen_gt && munge) { /* there is almost certainly a missing trailing quote mark as we have see too many newlines, < or > characters. an exception is made for Javascript attributes and the javascript URL scheme which may legitimately include < and >, and for attributes starting with "<xml " as generated by Microsoft Office. */ if ( !TY_(IsScript)(doc, name) && !(TY_(IsUrl)(doc, name) && TY_(tmbstrncmp)(lexer->lexbuf+start, "javascript:", 11) == 0) && !(TY_(tmbstrncmp)(lexer->lexbuf+start, "<xml ", 5) == 0) ) TY_(ReportFatal)( doc, NULL, NULL, SUSPECTED_MISSING_QUOTE ); } len = lexer->lexsize - start; lexer->lexsize = start; if (len > 0 || delim) { /* ignore leading and trailing white space for all but title, alt, value */ /* and prompts attributes unless --literal-attributes is set to yes */ /* #994841 - Whitespace is removed from value attributes */ if (munge && TY_(tmbstrcasecmp)(name, "alt") && TY_(tmbstrcasecmp)(name, "title") && TY_(tmbstrcasecmp)(name, "value") && TY_(tmbstrcasecmp)(name, "prompt")) { while (TY_(IsWhite)(lexer->lexbuf[start+len-1])) --len; while (TY_(IsWhite)(lexer->lexbuf[start]) && start < len) { ++start; --len; } } value = TY_(tmbstrndup)(doc->allocator, lexer->lexbuf + start, len); } else value = NULL; /* note delimiter if given */ *pdelim = (delim ? delim : '"'); return value; }
CWE-119
0
1
gxps_archive_input_stream_read (GInputStream *stream, void *buffer, gsize count, GCancellable *cancellable, GError **error) { GXPSArchiveInputStream *istream = GXPS_ARCHIVE_INPUT_STREAM (stream); gssize bytes_read; if (g_cancellable_set_error_if_cancelled (cancellable, error)) return -1; bytes_read = archive_read_data (istream->zip->archive, buffer, count); if (bytes_read == 0 && istream->is_interleaved && !gxps_archive_input_stream_is_last_piece (istream)) { /* Read next piece */ gxps_archive_input_stream_next_piece (istream); bytes_read = gxps_archive_input_stream_read (stream, buffer, count, cancellable, error); } return bytes_read; }
CWE-125
1
1
get_cookies (SoupCookieJar *jar, SoupURI *uri, gboolean for_http, gboolean copy_cookies) { SoupCookieJarPrivate *priv; GSList *cookies, *domain_cookies; char *domain, *cur, *next_domain; GSList *new_head, *cookies_to_remove = NULL, *p; priv = soup_cookie_jar_get_instance_private (jar); if (!uri->host) return NULL; /* The logic here is a little weird, but the plan is that if * uri->host is "www.foo.com", we will end up looking up * cookies for ".www.foo.com", "www.foo.com", ".foo.com", and * ".com", in that order. (Logic stolen from Mozilla.) */ cookies = NULL; domain = cur = g_strdup_printf (".%s", uri->host); next_domain = domain + 1; do { new_head = domain_cookies = g_hash_table_lookup (priv->domains, cur); while (domain_cookies) { GSList *next = domain_cookies->next; SoupCookie *cookie = domain_cookies->data; if (cookie->expires && soup_date_is_past (cookie->expires)) { cookies_to_remove = g_slist_append (cookies_to_remove, cookie); new_head = g_slist_delete_link (new_head, domain_cookies); g_hash_table_insert (priv->domains, g_strdup (cur), new_head); } else if (soup_cookie_applies_to_uri (cookie, uri) && (for_http || !cookie->http_only)) cookies = g_slist_append (cookies, copy_cookies ? soup_cookie_copy (cookie) : cookie); domain_cookies = next; } cur = next_domain; if (cur) next_domain = strchr (cur + 1, '.'); } while (cur); g_free (domain); for (p = cookies_to_remove; p; p = p->next) { SoupCookie *cookie = p->data; soup_cookie_jar_changed (jar, cookie, NULL); soup_cookie_free (cookie); } g_slist_free (cookies_to_remove); return g_slist_sort_with_data (cookies, compare_cookies, jar); }
CWE-125
1
1
bool read_ujpg( void ) { using namespace IOUtil; using namespace Sirikata; // colldata.start_decoder_worker_thread(std::bind(&simple_decoder, &colldata, str_in)); unsigned char ujpg_mrk[ 64 ]; // this is where we will enable seccomp, before reading user data write_byte_bill(Billing::HEADER, true, 24); // for the fixed header str_out->call_size_callback(max_file_size); uint32_t compressed_header_size = 0; if (ReadFull(str_in, ujpg_mrk, 4) != 4) { custom_exit(ExitCode::SHORT_READ); } write_byte_bill(Billing::HEADER, true, 4); compressed_header_size = LEtoUint32(ujpg_mrk); if (compressed_header_size > 128 * 1024 * 1024 || max_file_size > 128 * 1024 * 1024) { always_assert(false && "Only support images < 128 megs"); return false; // bool too big } bool pending_header_reads = false; if (header_reader == NULL) { std::vector<uint8_t, JpegAllocator<uint8_t> > compressed_header_buffer(compressed_header_size); IOUtil::ReadFull(str_in, compressed_header_buffer.data(), compressed_header_buffer.size()); header_reader = new MemReadWriter((JpegAllocator<uint8_t>())); { if (ujgversion == 1) { JpegAllocator<uint8_t> no_free_allocator; #if !defined(USE_STANDARD_MEMORY_ALLOCATORS) && !defined(_WIN32) && !defined(EMSCRIPTEN) no_free_allocator.setup_memory_subsystem(32 * 1024 * 1024, 16, &mem_init_nop, &MemMgrAllocatorMalloc, &mem_nop, &mem_realloc_nop, &MemMgrAllocatorMsize); #endif std::pair<std::vector<uint8_t, Sirikata::JpegAllocator<uint8_t> >, JpegError> uncompressed_header_buffer( ZlibDecoderDecompressionReader::Decompress(compressed_header_buffer.data(), compressed_header_buffer.size(), no_free_allocator, max_file_size + 2048)); if (uncompressed_header_buffer.second) { always_assert(false && "Data not properly zlib coded"); return false; } zlib_hdrs = compressed_header_buffer.size(); header_reader->SwapIn(uncompressed_header_buffer.first, 0); } else { std::pair<std::vector<uint8_t, Sirikata::JpegAllocator<uint8_t> >, JpegError> uncompressed_header_buffer( Sirikata::BrotliCodec::Decompress(compressed_header_buffer.data(), compressed_header_buffer.size(), JpegAllocator<uint8_t>(), max_file_size * 2 + 128 * 1024 * 1024)); if (uncompressed_header_buffer.second) { always_assert(false && "Data not properly zlib coded"); return false; } zlib_hdrs = compressed_header_buffer.size(); header_reader->SwapIn(uncompressed_header_buffer.first, 0); } } write_byte_bill(Billing::HEADER, true, compressed_header_buffer.size()); } else { always_assert(compressed_header_size == 0 && "Special concatenation requires 0 size header"); } grbs = sizeof(EOI); grbgdata = EOI; // if we don't have any garbage, assume FFD9 EOI // read header from file ReadFull(header_reader, ujpg_mrk, 3 ) ; // check marker if ( memcmp( ujpg_mrk, "HDR", 3 ) == 0 ) { // read size of header, alloc memory ReadFull(header_reader, ujpg_mrk, 4 ); hdrs = LEtoUint32(ujpg_mrk); hdrdata = (unsigned char*) aligned_alloc(hdrs); memset(hdrdata, 0, hdrs); if ( hdrdata == NULL ) { fprintf( stderr, MEM_ERRMSG ); errorlevel.store(2); return false; } // read hdrdata ReadFull(header_reader, hdrdata, hdrs ); } else { fprintf( stderr, "HDR marker not found" ); errorlevel.store(2); return false; } bool memory_optimized_image = (filetype != UJG) && !g_allow_progressive; // parse header for image-info if ( !setup_imginfo_jpg(memory_optimized_image) ) return false; // beginning here: recovery information (needed for exact JPEG recovery) // read padbit information from file ReadFull(header_reader, ujpg_mrk, 3 ); // check marker if ( memcmp( ujpg_mrk, "P0D", 3 ) == 0 ) { // This is a more nuanced pad byte that can have different values per bit header_reader->Read( reinterpret_cast<unsigned char*>(&padbit), 1 ); } else if ( memcmp( ujpg_mrk, "PAD", 3 ) == 0 ) { // this is a single pad bit that is implied to have all the same values header_reader->Read( reinterpret_cast<unsigned char*>(&padbit), 1 ); if (!(padbit == 0 || padbit == 1 ||padbit == -1)) { while (write(2, "Legacy Padbit must be 0, 1 or -1\n", strlen("Legacy Padbit must be 0, 1 or -1\n")) < 0 && errno == EINTR) { } custom_exit(ExitCode::STREAM_INCONSISTENT); } if (padbit == 1) { padbit = 0x7f; // all 6 bits set } } else { fprintf( stderr, "PAD marker not found" ); errorlevel.store(2); return false; } std::vector<ThreadHandoff> thread_handoff; // read further recovery information if any while ( ReadFull(header_reader, ujpg_mrk, 3 ) == 3 ) { // check marker if ( memcmp( ujpg_mrk, "CRS", 3 ) == 0 ) { rst_cnt_set = true; ReadFull(header_reader, ujpg_mrk, 4); rst_cnt.resize(LEtoUint32(ujpg_mrk)); for (size_t i = 0; i < rst_cnt.size(); ++i) { ReadFull(header_reader, ujpg_mrk, 4); rst_cnt.at(i) = LEtoUint32(ujpg_mrk); } } else if ( memcmp( ujpg_mrk, "HHX", 2 ) == 0 ) { // only look at first two bytes size_t to_alloc = ThreadHandoff::get_remaining_data_size_from_two_bytes(ujpg_mrk + 1) + 2; if(to_alloc) { std::vector<unsigned char> data(to_alloc); data[0] = ujpg_mrk[1]; data[1] = ujpg_mrk[2]; ReadFull(header_reader, &data[2], to_alloc - 2); thread_handoff = ThreadHandoff::deserialize(&data[0], to_alloc); } } else if ( memcmp( ujpg_mrk, "FRS", 3 ) == 0 ) { // read number of false set RST markers per scan from file ReadFull(header_reader, ujpg_mrk, 4); scnc = LEtoUint32(ujpg_mrk); rst_err.insert(rst_err.end(), scnc - rst_err.size(), 0); // read data ReadFull(header_reader, rst_err.data(), scnc ); } else if ( memcmp( ujpg_mrk, "GRB", 3 ) == 0 ) { // read garbage (data after end of JPG) from file ReadFull(header_reader, ujpg_mrk, 4); grbs = LEtoUint32(ujpg_mrk); grbgdata = aligned_alloc(grbs); memset(grbgdata, 0, sizeof(grbs)); if ( grbgdata == NULL ) { fprintf( stderr, MEM_ERRMSG ); errorlevel.store(2); return false; } // read garbage data ReadFull(header_reader, grbgdata, grbs ); } else if ( memcmp( ujpg_mrk, "PGR", 3 ) == 0 || memcmp( ujpg_mrk, "PGE", 3 ) == 0 ) { // read prefix garbage (data before beginning of JPG) from file if (ujpg_mrk[2] == 'E') { // embedded jpeg: full header required embedded_jpeg = true; } ReadFull(header_reader, ujpg_mrk, 4); prefix_grbs = LEtoUint32(ujpg_mrk); prefix_grbgdata = aligned_alloc(prefix_grbs); memset(prefix_grbgdata, 0, sizeof(prefix_grbs)); if ( prefix_grbgdata == NULL ) { fprintf( stderr, MEM_ERRMSG ); errorlevel.store(2); return false; } // read garbage data ReadFull(header_reader, prefix_grbgdata, prefix_grbs ); } else if ( memcmp( ujpg_mrk, "SIZ", 3 ) == 0 ) { // full size of the original file ReadFull(header_reader, ujpg_mrk, 4); max_file_size = LEtoUint32(ujpg_mrk); } else if ( memcmp( ujpg_mrk, "EEE", 3) == 0) { ReadFull(header_reader, ujpg_mrk, 28); max_cmp = LEtoUint32(ujpg_mrk); max_bpos = LEtoUint32(ujpg_mrk + 4); max_sah = LEtoUint32(ujpg_mrk + 8); max_dpos[0] = LEtoUint32(ujpg_mrk + 12); max_dpos[1] = LEtoUint32(ujpg_mrk + 16); max_dpos[2] = LEtoUint32(ujpg_mrk + 20); max_dpos[3] = LEtoUint32(ujpg_mrk + 24); early_eof_encountered = true; colldata.set_truncation_bounds(max_cmp, max_bpos, max_dpos, max_sah); } else { if (memcmp(ujpg_mrk, "CNT", 3) == 0 ) { pending_header_reads = true; break; } else if (memcmp(ujpg_mrk, "CMP", 3) == 0 ) { break; } else { fprintf( stderr, "unknown data found" ); errorlevel.store(2); } return false; } } if (!pending_header_reads) { delete header_reader; header_reader = NULL; } write_byte_bill(Billing::HEADER, false, 2 + hdrs + prefix_grbs + grbs); ReadFull(str_in, ujpg_mrk, 3 ) ; write_byte_bill(Billing::HEADER, true, 3); write_byte_bill(Billing::DELIMITERS, true, 4 * NUM_THREADS); // trailing vpx_encode bits write_byte_bill(Billing::HEADER, true, 4); //trailing size if (memcmp(ujpg_mrk, "CMP", 3) != 0) { always_assert(false && "CMP must be present (uncompressed) in the file or CNT continue marker"); return false; // not a JPG } colldata.signal_worker_should_begin(); g_decoder->initialize(str_in, thread_handoff); colldata.start_decoder(g_decoder); return true; }
CWE-399
4
1
tcf_fill_node(struct sk_buff *skb, struct tcf_proto *tp, unsigned long fh, u32 pid, u32 seq, u16 flags, int event) { struct tcmsg *tcm; struct nlmsghdr *nlh; unsigned char *b = skb->tail; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*tcm), flags); tcm = NLMSG_DATA(nlh); tcm->tcm_family = AF_UNSPEC; tcm->tcm_ifindex = tp->q->dev->ifindex; tcm->tcm_parent = tp->classid; tcm->tcm_info = TC_H_MAKE(tp->prio, tp->protocol); RTA_PUT(skb, TCA_KIND, IFNAMSIZ, tp->ops->kind); tcm->tcm_handle = fh; if (RTM_DELTFILTER != event) { tcm->tcm_handle = 0; if (tp->ops->dump && tp->ops->dump(tp, fh, skb, tcm) < 0) goto rtattr_failure; } nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
CWE-200
3
0
static inline void async_read_clear_handlers(AsyncRead *obj) { ssize_t ret; if (!s->sasl.encoded) { int err; err = sasl_encode(s->sasl.conn, (char *)buf, nbyte, (const char **)&s->sasl.encoded, &s->sasl.encodedLength); if (err != SASL_OK) { spice_warning("sasl_encode error: %d", err); return -1; } if (s->sasl.encodedLength == 0) { return 0; } if (!s->sasl.encoded) { spice_warning("sasl_encode didn't return a buffer!"); return 0; } s->sasl.encodedOffset = 0; } ret = s->write(s, s->sasl.encoded + s->sasl.encodedOffset, s->sasl.encodedLength - s->sasl.encodedOffset); if (ret <= 0) { return ret; } s->sasl.encodedOffset += ret; if (s->sasl.encodedOffset == s->sasl.encodedLength) { s->sasl.encoded = NULL; s->sasl.encodedOffset = s->sasl.encodedLength = 0; return nbyte; } /* we didn't flush the encoded buffer */ errno = EAGAIN; return -1; }
none
8
0
void GfxColorSpace::getGrayLine(Guchar *in, unsigned char *out, int length) { int i, j, n; GfxColor color; GfxGray gray; n = getNComps(); for (i = 0; i < length; i++) { for (j = 0; j < n; j++) color.c[j] = in[i * n + j] * 256; getGray (&color, &gray); out[i] = colToByte(gray); } }
none
8
1
mix_pool(unsigned char *pool) { static unsigned char failsafe_digest[DIGESTLEN]; static int failsafe_digest_valid; unsigned char *hashbuf = pool + POOLSIZE; unsigned char *p, *pend; int i, n; SHA1_CONTEXT md; unsigned int nburn; #if DIGESTLEN != 20 #error must have a digest length of 20 for SHA-1 #endif gcry_assert (pool_is_locked); _gcry_sha1_mixblock_init (&md); /* Loop over the pool. */ pend = pool + POOLSIZE; memcpy (hashbuf, pend - DIGESTLEN, DIGESTLEN ); memcpy (hashbuf+DIGESTLEN, pool, BLOCKLEN-DIGESTLEN); nburn = _gcry_sha1_mixblock (&md, hashbuf); memcpy (pool, hashbuf, DIGESTLEN); if (failsafe_digest_valid && pool == rndpool) { for (i=0; i < DIGESTLEN; i++) pool[i] ^= failsafe_digest[i]; } p = pool; for (n=1; n < POOLBLOCKS; n++) { memcpy (hashbuf, p, DIGESTLEN); p += DIGESTLEN; if (p+DIGESTLEN+BLOCKLEN < pend) memcpy (hashbuf+DIGESTLEN, p+DIGESTLEN, BLOCKLEN-DIGESTLEN); else { unsigned char *pp = p + DIGESTLEN; for (i=DIGESTLEN; i < BLOCKLEN; i++ ) { if ( pp >= pend ) pp = pool; hashbuf[i] = *pp++; } } _gcry_sha1_mixblock (&md, hashbuf); memcpy(p, hashbuf, DIGESTLEN); } /* Our hash implementation does only leave small parts (64 bytes) of the pool on the stack, so it is okay not to require secure memory here. Before we use this pool, it will be copied to the help buffer anyway. */ if ( pool == rndpool) { _gcry_sha1_hash_buffer (failsafe_digest, pool, POOLSIZE); failsafe_digest_valid = 1; } _gcry_burn_stack (nburn); }
CWE-200
3
1
mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy) { mrb_value orig; mrb_value buf; struct mrb_io *fptr_copy; struct mrb_io *fptr_orig; mrb_bool failed = TRUE; mrb_get_args(mrb, "o", &orig); fptr_copy = (struct mrb_io *)DATA_PTR(copy); if (fptr_copy != NULL) { fptr_finalize(mrb, fptr_copy, FALSE); mrb_free(mrb, fptr_copy); } fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb); fptr_orig = io_get_open_fptr(mrb, orig); DATA_TYPE(copy) = &mrb_io_type; DATA_PTR(copy) = fptr_copy; buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, "@buf")); mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, "@buf"), buf); fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed); if (failed) { mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd); if (fptr_orig->fd2 != -1) { fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed); if (failed) { close(fptr_copy->fd); mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd2); } fptr_copy->pid = fptr_orig->pid; fptr_copy->readable = fptr_orig->readable; fptr_copy->writable = fptr_orig->writable; fptr_copy->sync = fptr_orig->sync; fptr_copy->is_socket = fptr_orig->is_socket; return copy; }
CWE-416
5
1
isdn_ioctl(struct inode *inode, struct file *file, uint cmd, ulong arg) { uint minor = iminor(inode); isdn_ctrl c; int drvidx; int chidx; int ret; int i; char __user *p; char *s; union iocpar { char name[10]; char bname[22]; isdn_ioctl_struct iocts; isdn_net_ioctl_phone phone; isdn_net_ioctl_cfg cfg; } iocpar; void __user *argp = (void __user *)arg; #define name iocpar.name #define bname iocpar.bname #define iocts iocpar.iocts #define phone iocpar.phone #define cfg iocpar.cfg if (minor == ISDN_MINOR_STATUS) { switch (cmd) { case IIOCGETDVR: return (TTY_DV + (NET_DV << 8) + (INF_DV << 16)); case IIOCGETCPS: if (arg) { ulong __user *p = argp; int i; if (!access_ok(VERIFY_WRITE, p, sizeof(ulong) * ISDN_MAX_CHANNELS * 2)) return -EFAULT; for (i = 0; i < ISDN_MAX_CHANNELS; i++) { put_user(dev->ibytes[i], p++); put_user(dev->obytes[i], p++); } return 0; } else return -EINVAL; break; #ifdef CONFIG_NETDEVICES case IIOCNETGPN: /* Get peer phone number of a connected * isdn network interface */ if (arg) { if (copy_from_user(&phone, argp, sizeof(phone))) return -EFAULT; return isdn_net_getpeer(&phone, argp); } else return -EINVAL; #endif default: return -EINVAL; } } if (!dev->drivers) return -ENODEV; if (minor <= ISDN_MINOR_BMAX) { drvidx = isdn_minor2drv(minor); if (drvidx < 0) return -ENODEV; chidx = isdn_minor2chan(minor); if (!(dev->drv[drvidx]->flags & DRV_FLAG_RUNNING)) return -ENODEV; return 0; } if (minor <= ISDN_MINOR_CTRLMAX) { /* * isdn net devices manage lots of configuration variables as linked lists. * Those lists must only be manipulated from user space. Some of the ioctl's * service routines access user space and are not atomic. Therefor, ioctl's * manipulating the lists and ioctl's sleeping while accessing the lists * are serialized by means of a semaphore. */ switch (cmd) { case IIOCNETDWRSET: printk(KERN_INFO "INFO: ISDN_DW_ABC_EXTENSION not enabled\n"); return(-EINVAL); case IIOCNETLCR: printk(KERN_INFO "INFO: ISDN_ABC_LCR_SUPPORT not enabled\n"); return -ENODEV; #ifdef CONFIG_NETDEVICES case IIOCNETAIF: /* Add a network-interface */ if (arg) { if (copy_from_user(name, argp, sizeof(name))) return -EFAULT; s = name; } else { s = NULL; } ret = mutex_lock_interruptible(&dev->mtx); if( ret ) return ret; if ((s = isdn_net_new(s, NULL))) { if (copy_to_user(argp, s, strlen(s) + 1)){ ret = -EFAULT; } else { ret = 0; } } else ret = -ENODEV; mutex_unlock(&dev->mtx); return ret; case IIOCNETASL: /* Add a slave to a network-interface */ if (arg) { if (copy_from_user(bname, argp, sizeof(bname) - 1)) return -EFAULT; } else return -EINVAL; ret = mutex_lock_interruptible(&dev->mtx); if( ret ) return ret; if ((s = isdn_net_newslave(bname))) { if (copy_to_user(argp, s, strlen(s) + 1)){ ret = -EFAULT; } else { ret = 0; } } else ret = -ENODEV; mutex_unlock(&dev->mtx); return ret; case IIOCNETDIF: /* Delete a network-interface */ if (arg) { if (copy_from_user(name, argp, sizeof(name))) return -EFAULT; ret = mutex_lock_interruptible(&dev->mtx); if( ret ) return ret; ret = isdn_net_rm(name); mutex_unlock(&dev->mtx); return ret; } else return -EINVAL; case IIOCNETSCF: /* Set configurable parameters of a network-interface */ if (arg) { if (copy_from_user(&cfg, argp, sizeof(cfg))) return -EFAULT; return isdn_net_setcfg(&cfg); } else return -EINVAL; case IIOCNETGCF: /* Get configurable parameters of a network-interface */ if (arg) { if (copy_from_user(&cfg, argp, sizeof(cfg))) return -EFAULT; if (!(ret = isdn_net_getcfg(&cfg))) { if (copy_to_user(argp, &cfg, sizeof(cfg))) return -EFAULT; } return ret; } else return -EINVAL; case IIOCNETANM: /* Add a phone-number to a network-interface */ if (arg) { if (copy_from_user(&phone, argp, sizeof(phone))) return -EFAULT; ret = mutex_lock_interruptible(&dev->mtx); if( ret ) return ret; ret = isdn_net_addphone(&phone); mutex_unlock(&dev->mtx); return ret; } else return -EINVAL; case IIOCNETGNM: /* Get list of phone-numbers of a network-interface */ if (arg) { if (copy_from_user(&phone, argp, sizeof(phone))) return -EFAULT; ret = mutex_lock_interruptible(&dev->mtx); if( ret ) return ret; ret = isdn_net_getphones(&phone, argp); mutex_unlock(&dev->mtx); return ret; } else return -EINVAL; case IIOCNETDNM: /* Delete a phone-number of a network-interface */ if (arg) { if (copy_from_user(&phone, argp, sizeof(phone))) return -EFAULT; ret = mutex_lock_interruptible(&dev->mtx); if( ret ) return ret; ret = isdn_net_delphone(&phone); mutex_unlock(&dev->mtx); return ret; } else return -EINVAL; case IIOCNETDIL: /* Force dialing of a network-interface */ if (arg) { if (copy_from_user(name, argp, sizeof(name))) return -EFAULT; return isdn_net_force_dial(name); } else return -EINVAL; #ifdef CONFIG_ISDN_PPP case IIOCNETALN: if (!arg) return -EINVAL; if (copy_from_user(name, argp, sizeof(name))) return -EFAULT; return isdn_ppp_dial_slave(name); case IIOCNETDLN: if (!arg) return -EINVAL; if (copy_from_user(name, argp, sizeof(name))) return -EFAULT; return isdn_ppp_hangup_slave(name); #endif case IIOCNETHUP: /* Force hangup of a network-interface */ if (!arg) return -EINVAL; if (copy_from_user(name, argp, sizeof(name))) return -EFAULT; return isdn_net_force_hangup(name); break; #endif /* CONFIG_NETDEVICES */ case IIOCSETVER: dev->net_verbose = arg; printk(KERN_INFO "isdn: Verbose-Level is %d\n", dev->net_verbose); return 0; case IIOCSETGST: if (arg) dev->global_flags |= ISDN_GLOBAL_STOPPED; else dev->global_flags &= ~ISDN_GLOBAL_STOPPED; printk(KERN_INFO "isdn: Global Mode %s\n", (dev->global_flags & ISDN_GLOBAL_STOPPED) ? "stopped" : "running"); return 0; case IIOCSETBRJ: drvidx = -1; if (arg) { int i; char *p; if (copy_from_user(&iocts, argp, sizeof(isdn_ioctl_struct))) return -EFAULT; if (strlen(iocts.drvid)) { if ((p = strchr(iocts.drvid, ','))) *p = 0; drvidx = -1; for (i = 0; i < ISDN_MAX_DRIVERS; i++) if (!(strcmp(dev->drvid[i], iocts.drvid))) { drvidx = i; break; } } } if (drvidx == -1) return -ENODEV; if (iocts.arg) dev->drv[drvidx]->flags |= DRV_FLAG_REJBUS; else dev->drv[drvidx]->flags &= ~DRV_FLAG_REJBUS; return 0; case IIOCSIGPRF: dev->profd = current; return 0; break; case IIOCGETPRF: /* Get all Modem-Profiles */ if (arg) { char __user *p = argp; int i; if (!access_ok(VERIFY_WRITE, argp, (ISDN_MODEM_NUMREG + ISDN_MSNLEN + ISDN_LMSNLEN) * ISDN_MAX_CHANNELS)) return -EFAULT; for (i = 0; i < ISDN_MAX_CHANNELS; i++) { if (copy_to_user(p, dev->mdm.info[i].emu.profile, ISDN_MODEM_NUMREG)) return -EFAULT; p += ISDN_MODEM_NUMREG; if (copy_to_user(p, dev->mdm.info[i].emu.pmsn, ISDN_MSNLEN)) return -EFAULT; p += ISDN_MSNLEN; if (copy_to_user(p, dev->mdm.info[i].emu.plmsn, ISDN_LMSNLEN)) return -EFAULT; p += ISDN_LMSNLEN; } return (ISDN_MODEM_NUMREG + ISDN_MSNLEN + ISDN_LMSNLEN) * ISDN_MAX_CHANNELS; } else return -EINVAL; break; case IIOCSETPRF: /* Set all Modem-Profiles */ if (arg) { char __user *p = argp; int i; if (!access_ok(VERIFY_READ, argp, (ISDN_MODEM_NUMREG + ISDN_MSNLEN + ISDN_LMSNLEN) * ISDN_MAX_CHANNELS)) return -EFAULT; for (i = 0; i < ISDN_MAX_CHANNELS; i++) { if (copy_from_user(dev->mdm.info[i].emu.profile, p, ISDN_MODEM_NUMREG)) return -EFAULT; p += ISDN_MODEM_NUMREG; if (copy_from_user(dev->mdm.info[i].emu.plmsn, p, ISDN_LMSNLEN)) return -EFAULT; p += ISDN_LMSNLEN; if (copy_from_user(dev->mdm.info[i].emu.pmsn, p, ISDN_MSNLEN)) return -EFAULT; p += ISDN_MSNLEN; } return 0; } else return -EINVAL; break; case IIOCSETMAP: case IIOCGETMAP: /* Set/Get MSN->EAZ-Mapping for a driver */ if (arg) { if (copy_from_user(&iocts, argp, sizeof(isdn_ioctl_struct))) return -EFAULT; if (strlen(iocts.drvid)) { drvidx = -1; for (i = 0; i < ISDN_MAX_DRIVERS; i++) if (!(strcmp(dev->drvid[i], iocts.drvid))) { drvidx = i; break; } } else drvidx = 0; if (drvidx == -1) return -ENODEV; if (cmd == IIOCSETMAP) { int loop = 1; p = (char __user *) iocts.arg; i = 0; while (loop) { int j = 0; while (1) { if (!access_ok(VERIFY_READ, p, 1)) return -EFAULT; get_user(bname[j], p++); switch (bname[j]) { case '\0': loop = 0; /* Fall through */ case ',': bname[j] = '\0'; strcpy(dev->drv[drvidx]->msn2eaz[i], bname); j = ISDN_MSNLEN; break; default: j++; } if (j >= ISDN_MSNLEN) break; } if (++i > 9) break; } } else { p = (char __user *) iocts.arg; for (i = 0; i < 10; i++) { sprintf(bname, "%s%s", strlen(dev->drv[drvidx]->msn2eaz[i]) ? dev->drv[drvidx]->msn2eaz[i] : "_", (i < 9) ? "," : "\0"); if (copy_to_user(p, bname, strlen(bname) + 1)) return -EFAULT; p += strlen(bname); } } return 0; } else return -EINVAL; case IIOCDBGVAR: if (arg) { if (copy_to_user(argp, &dev, sizeof(ulong))) return -EFAULT; return 0; } else return -EINVAL; break; default: if ((cmd & IIOCDRVCTL) == IIOCDRVCTL) cmd = ((cmd >> _IOC_NRSHIFT) & _IOC_NRMASK) & ISDN_DRVIOCTL_MASK; else return -EINVAL; if (arg) { int i; char *p; if (copy_from_user(&iocts, argp, sizeof(isdn_ioctl_struct))) return -EFAULT; if (strlen(iocts.drvid)) { if ((p = strchr(iocts.drvid, ','))) *p = 0; drvidx = -1; for (i = 0; i < ISDN_MAX_DRIVERS; i++) if (!(strcmp(dev->drvid[i], iocts.drvid))) { drvidx = i; break; } } else drvidx = 0; if (drvidx == -1) return -ENODEV; if (!access_ok(VERIFY_WRITE, argp, sizeof(isdn_ioctl_struct))) return -EFAULT; c.driver = drvidx; c.command = ISDN_CMD_IOCTL; c.arg = cmd; memcpy(c.parm.num, &iocts.arg, sizeof(ulong)); ret = isdn_command(&c); memcpy(&iocts.arg, c.parm.num, sizeof(ulong)); if (copy_to_user(argp, &iocts, sizeof(isdn_ioctl_struct))) return -EFAULT; return ret; } else return -EINVAL; } } #ifdef CONFIG_ISDN_PPP if (minor <= ISDN_MINOR_PPPMAX) return (isdn_ppp_ioctl(minor - ISDN_MINOR_PPP, file, cmd, arg)); #endif return -ENODEV; #undef name #undef bname #undef iocts #undef phone #undef cfg }
CWE-119
0
1
static int magicmouse_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct magicmouse_sc *msc = hid_get_drvdata(hdev); struct input_dev *input = msc->input; int x = 0, y = 0, ii, clicks = 0, npoints; switch (data[0]) { case TRACKPAD_REPORT_ID: /* Expect four bytes of prefix, and N*9 bytes of touch data. */ if (size < 4 || ((size - 4) % 9) != 0) return 0; npoints = (size - 4) / 9; msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 9 + 4); clicks = data[1]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[1] >> 6 | data[2] << 2 | data[3] << 10; */ break; case MOUSE_REPORT_ID: /* Expect six bytes of prefix, and N*8 bytes of touch data. */ if (size < 6 || ((size - 6) % 8) != 0) return 0; npoints = (size - 6) / 8; msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 8 + 6); /* When emulating three-button mode, it is important * to have the current touch information before * generating a click event. */ x = (int)(((data[3] & 0x0c) << 28) | (data[1] << 22)) >> 22; y = (int)(((data[3] & 0x30) << 26) | (data[2] << 22)) >> 22; clicks = data[3]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[3] >> 6 | data[4] << 2 | data[5] << 10; */ break; case DOUBLE_REPORT_ID: /* Sometimes the trackpad sends two touch reports in one * packet. */ magicmouse_raw_event(hdev, report, data + 2, data[1]); magicmouse_raw_event(hdev, report, data + 2 + data[1], size - 2 - data[1]); break; default: return 0; } if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE) { magicmouse_emit_buttons(msc, clicks & 3); input_report_rel(input, REL_X, x); input_report_rel(input, REL_Y, y); } else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */ input_report_key(input, BTN_MOUSE, clicks & 1); input_mt_report_pointer_emulation(input, true); } input_sync(input); return 1; }
CWE-119
0
1
int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { struct page *page = NULL; struct rds_atomic_args *args; int ret = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args)) || rm->atomic.op_active) return -EINVAL; args = CMSG_DATA(cmsg); /* Nonmasked & masked cmsg ops converted to masked hw ops */ switch (cmsg->cmsg_type) { case RDS_CMSG_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->fadd.add; rm->atomic.op_m_fadd.nocarry_mask = 0; break; case RDS_CMSG_MASKED_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->m_fadd.add; rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask; break; case RDS_CMSG_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->cswp.compare; rm->atomic.op_m_cswp.swap = args->cswp.swap; rm->atomic.op_m_cswp.compare_mask = ~0; rm->atomic.op_m_cswp.swap_mask = ~0; break; case RDS_CMSG_MASKED_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->m_cswp.compare; rm->atomic.op_m_cswp.swap = args->m_cswp.swap; rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask; rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask; break; default: BUG(); /* should never happen */ } rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT); rm->atomic.op_active = 1; rm->atomic.op_recverr = rs->rs_recverr; rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1); if (!rm->atomic.op_sg) { ret = -ENOMEM; goto err; } /* verify 8 byte-aligned */ if (args->local_addr & 0x7) { ret = -EFAULT; goto err; } ret = rds_pin_pages(args->local_addr, 1, &page, 1); if (ret != 1) goto err; ret = 0; sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr)); if (rm->atomic.op_notify || rm->atomic.op_recverr) { /* We allocate an uninitialized notifier here, because * we don't want to do that in the completion handler. We * would have to use GFP_ATOMIC there, and don't want to deal * with failed allocations. */ rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL); if (!rm->atomic.op_notifier) { ret = -ENOMEM; goto err; } rm->atomic.op_notifier->n_user_token = args->user_token; rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS; } rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie); rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie); return ret; err: if (page) put_page(page); kfree(rm->atomic.op_notifier); return ret; }
CWE-476
6
1
static VALUE cParser_initialize(int argc, VALUE *argv, VALUE self) { VALUE source, opts; GET_PARSER_INIT; if (json->Vsource) { rb_raise(rb_eTypeError, "already initialized instance"); } #ifdef HAVE_RB_SCAN_ARGS_OPTIONAL_HASH rb_scan_args(argc, argv, "1:", &source, &opts); #else rb_scan_args(argc, argv, "11", &source, &opts); #endif if (!NIL_P(opts)) { #ifndef HAVE_RB_SCAN_ARGS_OPTIONAL_HASH opts = rb_convert_type(opts, T_HASH, "Hash", "to_hash"); if (NIL_P(opts)) { rb_raise(rb_eArgError, "opts needs to be like a hash"); } else { #endif VALUE tmp = ID2SYM(i_max_nesting); if (option_given_p(opts, tmp)) { VALUE max_nesting = rb_hash_aref(opts, tmp); if (RTEST(max_nesting)) { Check_Type(max_nesting, T_FIXNUM); json->max_nesting = FIX2INT(max_nesting); } else { json->max_nesting = 0; } } else { json->max_nesting = 100; } tmp = ID2SYM(i_allow_nan); if (option_given_p(opts, tmp)) { json->allow_nan = RTEST(rb_hash_aref(opts, tmp)) ? 1 : 0; } else { json->allow_nan = 0; } tmp = ID2SYM(i_symbolize_names); if (option_given_p(opts, tmp)) { json->symbolize_names = RTEST(rb_hash_aref(opts, tmp)) ? 1 : 0; } else { json->symbolize_names = 0; } tmp = ID2SYM(i_create_additions); if (option_given_p(opts, tmp)) { json->create_additions = RTEST(rb_hash_aref(opts, tmp)); } else { json->create_additions = 0; } if (json->symbolize_names && json->create_additions) { rb_raise(rb_eArgError, "options :symbolize_names and :create_additions cannot be " " used in conjunction"); } tmp = ID2SYM(i_create_id); if (option_given_p(opts, tmp)) { json->create_id = rb_hash_aref(opts, tmp); } else { json->create_id = rb_funcall(mJSON, i_create_id, 0); } tmp = ID2SYM(i_object_class); if (option_given_p(opts, tmp)) { json->object_class = rb_hash_aref(opts, tmp); } else { json->object_class = Qnil; } tmp = ID2SYM(i_array_class); if (option_given_p(opts, tmp)) { json->array_class = rb_hash_aref(opts, tmp); } else { json->array_class = Qnil; } tmp = ID2SYM(i_decimal_class); if (option_given_p(opts, tmp)) { json->decimal_class = rb_hash_aref(opts, tmp); } else { json->decimal_class = Qnil; } tmp = ID2SYM(i_match_string); if (option_given_p(opts, tmp)) { VALUE match_string = rb_hash_aref(opts, tmp); json->match_string = RTEST(match_string) ? match_string : Qnil; } else { json->match_string = Qnil; } #ifndef HAVE_RB_SCAN_ARGS_OPTIONAL_HASH } #endif } else { json->max_nesting = 100; json->allow_nan = 0; json->create_additions = 1; json->create_id = rb_funcall(mJSON, i_create_id, 0); json->object_class = Qnil; json->array_class = Qnil; json->decimal_class = Qnil; } source = convert_encoding(StringValue(source)); StringValue(source); json->len = RSTRING_LEN(source); json->source = RSTRING_PTR(source);; json->Vsource = source; return self; }
CWE-20
2
0
static int nfs_read_req(struct file_priv *priv, uint64_t offset, uint32_t readlen) { uint32_t data[1024]; uint32_t *p; int len; struct packet *nfs_packet; uint32_t rlen, eof; /* * struct READ3args { * nfs_fh3 file; * offset3 offset; * count3 count; * }; * * struct READ3resok { * post_op_attr file_attributes; * count3 count; * bool eof; * opaque data<>; * }; * * struct READ3resfail { * post_op_attr file_attributes; * }; * * union READ3res switch (nfsstat3 status) { * case NFS3_OK: * READ3resok resok; * default: * READ3resfail resfail; * }; */ p = &(data[0]); p = rpc_add_credentials(p); p = nfs_add_fh3(p, &priv->fh); p = nfs_add_uint64(p, offset); p = nfs_add_uint32(p, readlen); len = p - &(data[0]); nfs_packet = rpc_req(priv->npriv, PROG_NFS, NFSPROC3_READ, data, len); if (IS_ERR(nfs_packet)) return PTR_ERR(nfs_packet); p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4; p = nfs_read_post_op_attr(p, NULL); rlen = ntoh32(net_read_uint32(p)); /* skip over count */ p += 1; eof = ntoh32(net_read_uint32(p)); /* * skip over eof and count embedded in the representation of data * assuming it equals rlen above. */ p += 2; if (readlen && !rlen && !eof) { free(nfs_packet); return -EIO; } kfifo_put(priv->fifo, (char *)p, rlen); free(nfs_packet); return 0; }
none
8
1
rsvp_obj_print(netdissect_options *ndo, const u_char *pptr, u_int plen, const u_char *tptr, const char *ident, u_int tlen, const struct rsvp_common_header *rsvp_com_header) { const struct rsvp_object_header *rsvp_obj_header; const u_char *obj_tptr; union { const struct rsvp_obj_integrity_t *rsvp_obj_integrity; const struct rsvp_obj_frr_t *rsvp_obj_frr; } obj_ptr; u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen; int hexdump,processed,padbytes,error_code,error_value,i,sigcheck; union { float f; uint32_t i; } bw; uint8_t namelen; u_int action, subchannel; while(tlen>=sizeof(struct rsvp_object_header)) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header)); rsvp_obj_header = (const struct rsvp_object_header *)tptr; rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length); rsvp_obj_ctype=rsvp_obj_header->ctype; if(rsvp_obj_len % 4) { ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len)); return -1; } if(rsvp_obj_len < sizeof(struct rsvp_object_header)) { ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len, (unsigned long)sizeof(const struct rsvp_object_header))); return -1; } ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s", ident, tok2str(rsvp_obj_values, "Unknown", rsvp_obj_header->class_num), rsvp_obj_header->class_num, ((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject")); if (rsvp_obj_header->class_num > 128) ND_PRINT((ndo, " %s", ((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently")); ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u", tok2str(rsvp_ctype_values, "Unknown", ((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype), rsvp_obj_ctype, rsvp_obj_len)); if(tlen < rsvp_obj_len) { ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident)); return -1; } obj_tptr=tptr+sizeof(struct rsvp_object_header); obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header); /* did we capture enough for fully decoding the object ? */ if (!ND_TTEST2(*tptr, rsvp_obj_len)) return -1; hexdump=FALSE; switch(rsvp_obj_header->class_num) { case RSVP_OBJ_SESSION: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return -1; ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x", ident, ipaddr_string(ndo, obj_tptr), *(obj_tptr + sizeof(struct in_addr)))); ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u", ident, *(obj_tptr+5), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return -1; ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x", ident, ip6addr_string(ndo, obj_tptr), *(obj_tptr + sizeof(struct in6_addr)))); ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u", ident, *(obj_tptr+sizeof(struct in6_addr)+1), EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_TUNNEL_IPV6: if (obj_tlen < 36) return -1; ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ip6addr_string(ndo, obj_tptr + 20))); obj_tlen-=36; obj_tptr+=36; break; case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */ if (obj_tlen < 26) return -1; ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+6), ip6addr_string(ndo, obj_tptr + 8))); obj_tlen-=26; obj_tptr+=26; break; case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */ if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ipaddr_string(ndo, obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_TUNNEL_IPV4: case RSVP_CTYPE_UNI_IPV4: if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ipaddr_string(ndo, obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: hexdump=TRUE; } break; case RSVP_OBJ_CONFIRM: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < sizeof(struct in_addr)) return -1; ND_PRINT((ndo, "%s IPv4 Receiver Address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in_addr); obj_tptr+=sizeof(struct in_addr); break; case RSVP_CTYPE_IPV6: if (obj_tlen < sizeof(struct in6_addr)) return -1; ND_PRINT((ndo, "%s IPv6 Receiver Address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in6_addr); obj_tptr+=sizeof(struct in6_addr); break; default: hexdump=TRUE; } break; case RSVP_OBJ_NOTIFY_REQ: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < sizeof(struct in_addr)) return -1; ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in_addr); obj_tptr+=sizeof(struct in_addr); break; case RSVP_CTYPE_IPV6: if (obj_tlen < sizeof(struct in6_addr)) return-1; ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in6_addr); obj_tptr+=sizeof(struct in6_addr); break; default: hexdump=TRUE; } break; case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */ case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */ case RSVP_OBJ_RECOVERY_LABEL: /* fall through */ case RSVP_OBJ_LABEL: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; } break; case RSVP_CTYPE_2: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Generalized Label: %u", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; case RSVP_CTYPE_3: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u", ident, EXTRACT_32BITS(obj_tptr), ident, EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: hexdump=TRUE; } break; case RSVP_OBJ_STYLE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]", ident, tok2str(rsvp_resstyle_values, "Unknown", EXTRACT_24BITS(obj_tptr+1)), *(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_SENDER_TEMPLATE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ if (obj_tlen < 40) return-1; ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ident, ip6addr_string(ndo, obj_tptr+20), EXTRACT_16BITS(obj_tptr + 38))); obj_tlen-=40; obj_tptr+=40; break; case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ident, ipaddr_string(ndo, obj_tptr+8), EXTRACT_16BITS(obj_tptr + 12))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_LABEL_REQ: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); obj_tlen-=4; obj_tptr+=4; } break; case RSVP_CTYPE_2: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" )); ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u", ident, (EXTRACT_16BITS(obj_tptr+4))&0xfff, (EXTRACT_16BITS(obj_tptr + 6)) & 0xfff)); ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u", ident, (EXTRACT_16BITS(obj_tptr+8))&0xfff, (EXTRACT_16BITS(obj_tptr + 10)) & 0xfff)); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_3: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI", ident, (EXTRACT_32BITS(obj_tptr+4))&0x7fffff, (EXTRACT_32BITS(obj_tptr+8))&0x7fffff, (((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "", (((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : "")); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_4: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)", ident, tok2str(gmpls_encoding_values, "Unknown", *obj_tptr), *obj_tptr)); ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)", ident, tok2str(gmpls_switch_cap_values, "Unknown", *(obj_tptr+1)), *(obj_tptr+1), tok2str(gmpls_payload_values, "Unknown", EXTRACT_16BITS(obj_tptr+2)), EXTRACT_16BITS(obj_tptr + 2))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_RRO: case RSVP_OBJ_ERO: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: while(obj_tlen >= 4 ) { u_char length; ND_TCHECK2(*obj_tptr, 4); length = *(obj_tptr + 1); ND_PRINT((ndo, "%s Subobject Type: %s, length %u", ident, tok2str(rsvp_obj_xro_values, "Unknown %u", RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)), length)); if (length == 0) { /* prevent infinite loops */ ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident)); break; } switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) { u_char prefix_length; case RSVP_OBJ_XRO_IPV4: if (length != 8) { ND_PRINT((ndo, " ERROR: length != 8")); goto invalid; } ND_TCHECK2(*obj_tptr, 8); prefix_length = *(obj_tptr+6); if (prefix_length != 32) { ND_PRINT((ndo, " ERROR: Prefix length %u != 32", prefix_length)); goto invalid; } ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]", RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict", ipaddr_string(ndo, obj_tptr+2), *(obj_tptr+6), bittok2str(rsvp_obj_rro_flag_values, "none", *(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */ break; case RSVP_OBJ_XRO_LABEL: if (length != 8) { ND_PRINT((ndo, " ERROR: length != 8")); goto invalid; } ND_TCHECK2(*obj_tptr, 8); ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u", bittok2str(rsvp_obj_rro_label_flag_values, "none", *(obj_tptr+2)), *(obj_tptr+2), tok2str(rsvp_ctype_values, "Unknown", *(obj_tptr+3) + 256*RSVP_OBJ_RRO), *(obj_tptr+3), EXTRACT_32BITS(obj_tptr + 4))); } obj_tlen-=*(obj_tptr+1); obj_tptr+=*(obj_tptr+1); } break; default: hexdump=TRUE; } break; case RSVP_OBJ_HELLO: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: case RSVP_CTYPE_2: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; break; default: hexdump=TRUE; } break; case RSVP_OBJ_RESTART_CAPABILITY: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; break; default: hexdump=TRUE; } break; case RSVP_OBJ_SESSION_ATTRIBUTE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 4) return-1; namelen = *(obj_tptr+3); if (obj_tlen < 4+namelen) return-1; ND_PRINT((ndo, "%s Session Name: ", ident)); for (i = 0; i < namelen; i++) safeputchar(ndo, *(obj_tptr + 4 + i)); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)", ident, (int)*obj_tptr, (int)*(obj_tptr+1), bittok2str(rsvp_session_attribute_flag_values, "none", *(obj_tptr+2)), *(obj_tptr + 2))); obj_tlen-=4+*(obj_tptr+3); obj_tptr+=4+*(obj_tptr+3); break; default: hexdump=TRUE; } break; case RSVP_OBJ_GENERALIZED_UNI: switch(rsvp_obj_ctype) { int subobj_type,af,subobj_len,total_subobj_len; case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; /* read variable length subobjects */ total_subobj_len = obj_tlen; while(total_subobj_len > 0) { /* If RFC 3476 Section 3.1 defined that a sub-object of the * GENERALIZED_UNI RSVP object must have the Length field as * a multiple of 4, instead of the check below it would be * better to test total_subobj_len only once before the loop. * So long as it does not define it and this while loop does * not implement such a requirement, let's accept that within * each iteration subobj_len may happen to be a multiple of 1 * and test it and total_subobj_len respectively. */ if (total_subobj_len < 4) goto invalid; subobj_len = EXTRACT_16BITS(obj_tptr); subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8; af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF; ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u", ident, tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type), subobj_type, tok2str(af_values, "Unknown", af), af, subobj_len)); /* In addition to what is explained above, the same spec does not * explicitly say that the same Length field includes the 4-octet * sub-object header, but as long as this while loop implements it * as it does include, let's keep the check below consistent with * the rest of the code. */ if(subobj_len < 4 || subobj_len > total_subobj_len) goto invalid; switch(subobj_type) { case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS: case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS: switch(af) { case AFNUM_INET: if (subobj_len < 8) return -1; ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s", ident, ipaddr_string(ndo, obj_tptr + 4))); break; case AFNUM_INET6: if (subobj_len < 20) return -1; ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s", ident, ip6addr_string(ndo, obj_tptr + 4))); break; case AFNUM_NSAP: if (subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; } break; case RSVP_GEN_UNI_SUBOBJ_DIVERSITY: if (subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL: if (subobj_len < 16) { return -1; } ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u", ident, ((EXTRACT_32BITS(obj_tptr+4))>>31), ((EXTRACT_32BITS(obj_tptr+4))&0xFF), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr + 12))); break; case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL: if (subobj_len < 8) { return -1; } ND_PRINT((ndo, "%s Service level: %u", ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24)); break; default: hexdump=TRUE; break; } total_subobj_len-=subobj_len; obj_tptr+=subobj_len; obj_tlen+=subobj_len; } if (total_subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_RSVP_HOP: switch(rsvp_obj_ctype) { case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; if (obj_tlen) hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ break; case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr + 16))); obj_tlen-=20; obj_tptr+=20; hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ break; default: hexdump=TRUE; } break; case RSVP_OBJ_TIME_VALUES: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Refresh Period: %ums", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; /* those three objects do share the same semantics */ case RSVP_OBJ_SENDER_TSPEC: case RSVP_OBJ_ADSPEC: case RSVP_OBJ_FLOWSPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_2: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Msg-Version: %u, length: %u", ident, (*obj_tptr & 0xf0) >> 4, EXTRACT_16BITS(obj_tptr + 2) << 2)); obj_tptr+=4; /* get to the start of the service header */ obj_tlen-=4; while (obj_tlen >= 4) { intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2; ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u", ident, tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)), *(obj_tptr), (*(obj_tptr+1)&0x80) ? "" : "not", intserv_serv_tlen)); obj_tptr+=4; /* get to the start of the parameter list */ obj_tlen-=4; while (intserv_serv_tlen>=4) { processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen); if (processed == 0) break; obj_tlen-=processed; intserv_serv_tlen-=processed; obj_tptr+=processed; } } break; default: hexdump=TRUE; } break; case RSVP_OBJ_FILTERSPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_3: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_24BITS(obj_tptr + 17))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_TUNNEL_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ if (obj_tlen < 40) return-1; ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ident, ip6addr_string(ndo, obj_tptr+20), EXTRACT_16BITS(obj_tptr + 38))); obj_tlen-=40; obj_tptr+=40; break; case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ident, ipaddr_string(ndo, obj_tptr+8), EXTRACT_16BITS(obj_tptr + 12))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_FASTREROUTE: /* the differences between c-type 1 and 7 are minor */ obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr; switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: /* new style */ if (obj_tlen < sizeof(struct rsvp_obj_frr_t)) return-1; bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps", ident, (int)obj_ptr.rsvp_obj_frr->setup_prio, (int)obj_ptr.rsvp_obj_frr->hold_prio, (int)obj_ptr.rsvp_obj_frr->hop_limit, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all))); obj_tlen-=sizeof(struct rsvp_obj_frr_t); obj_tptr+=sizeof(struct rsvp_obj_frr_t); break; case RSVP_CTYPE_TUNNEL_IPV4: /* old style */ if (obj_tlen < 16) return-1; bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps", ident, (int)obj_ptr.rsvp_obj_frr->setup_prio, (int)obj_ptr.rsvp_obj_frr->hold_prio, (int)obj_ptr.rsvp_obj_frr->hop_limit, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_DETOUR: switch(rsvp_obj_ctype) { case RSVP_CTYPE_TUNNEL_IPV4: while(obj_tlen >= 8) { ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s", ident, ipaddr_string(ndo, obj_tptr), ipaddr_string(ndo, obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_CLASSTYPE: case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */ switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: ND_PRINT((ndo, "%s CT: %u", ident, EXTRACT_32BITS(obj_tptr) & 0x7)); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_ERROR_SPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; error_code=*(obj_tptr+5); error_value=EXTRACT_16BITS(obj_tptr+6); ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)", ident, ipaddr_string(ndo, obj_tptr), *(obj_tptr+4), ident, tok2str(rsvp_obj_error_code_values,"unknown",error_code), error_code)); switch (error_code) { case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value), error_value)); break; case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */ case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value), error_value)); break; default: ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value)); break; } obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; error_code=*(obj_tptr+17); error_value=EXTRACT_16BITS(obj_tptr+18); ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)", ident, ip6addr_string(ndo, obj_tptr), *(obj_tptr+16), ident, tok2str(rsvp_obj_error_code_values,"unknown",error_code), error_code)); switch (error_code) { case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value), error_value)); break; default: break; } obj_tlen-=20; obj_tptr+=20; break; default: hexdump=TRUE; } break; case RSVP_OBJ_PROPERTIES: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; padbytes = EXTRACT_16BITS(obj_tptr+2); ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u", ident, EXTRACT_16BITS(obj_tptr), padbytes)); obj_tlen-=4; obj_tptr+=4; /* loop through as long there is anything longer than the TLV header (2) */ while(obj_tlen >= 2 + padbytes) { ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */ ident, tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr), *obj_tptr, *(obj_tptr + 1))); if (obj_tlen < *(obj_tptr+1)) return-1; if (*(obj_tptr+1) < 2) return -1; print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2); obj_tlen-=*(obj_tptr+1); obj_tptr+=*(obj_tptr+1); } break; default: hexdump=TRUE; } break; case RSVP_OBJ_MESSAGE_ID: /* fall through */ case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */ case RSVP_OBJ_MESSAGE_ID_LIST: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: case RSVP_CTYPE_2: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u", ident, *obj_tptr, EXTRACT_24BITS(obj_tptr + 1))); obj_tlen-=4; obj_tptr+=4; /* loop through as long there are no messages left */ while(obj_tlen >= 4) { ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_INTEGRITY: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < sizeof(struct rsvp_obj_integrity_t)) return-1; obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr; ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]", ident, EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4), bittok2str(rsvp_obj_integrity_flag_values, "none", obj_ptr.rsvp_obj_integrity->flags))); ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12))); sigcheck = signature_verify(ndo, pptr, plen, obj_ptr.rsvp_obj_integrity->digest, rsvp_clear_checksum, rsvp_com_header); ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck))); obj_tlen+=sizeof(struct rsvp_obj_integrity_t); obj_tptr+=sizeof(struct rsvp_obj_integrity_t); break; default: hexdump=TRUE; } break; case RSVP_OBJ_ADMIN_STATUS: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Flags [%s]", ident, bittok2str(rsvp_obj_admin_status_flag_values, "none", EXTRACT_32BITS(obj_tptr)))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_LABEL_SET: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; action = (EXTRACT_16BITS(obj_tptr)>>8); ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident, tok2str(rsvp_obj_label_set_action_values, "Unknown", action), action, ((EXTRACT_32BITS(obj_tptr) & 0x7F)))); switch (action) { case LABEL_SET_INCLUSIVE_RANGE: case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */ /* only a couple of subchannels are expected */ if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident, EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: obj_tlen-=4; obj_tptr+=4; subchannel = 1; while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel, EXTRACT_32BITS(obj_tptr))); obj_tptr+=4; obj_tlen-=4; subchannel++; } break; } break; default: hexdump=TRUE; } case RSVP_OBJ_S2L: switch (rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Sub-LSP destination address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s Sub-LSP destination address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } /* * FIXME those are the defined objects that lack a decoder * you are welcome to contribute code ;-) */ case RSVP_OBJ_SCOPE: case RSVP_OBJ_POLICY_DATA: case RSVP_OBJ_ACCEPT_LABEL_SET: case RSVP_OBJ_PROTECTION: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */ break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || hexdump == TRUE) print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */ rsvp_obj_len - sizeof(struct rsvp_object_header)); tptr+=rsvp_obj_len; tlen-=rsvp_obj_len; } return 0; invalid: ND_PRINT((ndo, "%s", istr)); return -1; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return -1; }
CWE-125
1
1
ppp_hdlc(netdissect_options *ndo, const u_char *p, int length) { u_char *b, *s, *t, c; int i, proto; const void *se; if (length <= 0) return; b = (uint8_t *)malloc(length); if (b == NULL) return; /* * Unescape all the data into a temporary, private, buffer. * Do this so that we dont overwrite the original packet * contents. */ for (s = (u_char *)p, t = b, i = length; i > 0; i--) { c = *s++; if (c == 0x7d) { if (i > 1) { i--; c = *s++ ^ 0x20; } else continue; } *t++ = c; } se = ndo->ndo_snapend; ndo->ndo_snapend = t; length = t - b; /* now lets guess about the payload codepoint format */ if (length < 1) goto trunc; proto = *b; /* start with a one-octet codepoint guess */ switch (proto) { case PPP_IP: ip_print(ndo, b + 1, length - 1); goto cleanup; case PPP_IPV6: ip6_print(ndo, b + 1, length - 1); goto cleanup; default: /* no luck - try next guess */ break; } if (length < 2) goto trunc; proto = EXTRACT_16BITS(b); /* next guess - load two octets */ switch (proto) { case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */ if (length < 4) goto trunc; proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */ handle_ppp(ndo, proto, b + 4, length - 4); break; default: /* last guess - proto must be a PPP proto-id */ handle_ppp(ndo, proto, b + 2, length - 2); break; } cleanup: ndo->ndo_snapend = se; free(b); return; trunc: ndo->ndo_snapend = se; free(b); ND_PRINT((ndo, "[|ppp]")); }
CWE-119
0
0
zdevicename(i_ctx_t *i_ctx_p) { os_ptr op = osp; const char *dname; check_read_type(*op, t_device); if (op->value.pdevice == NULL) /* This can happen if we invalidated devices on the stack by calling nulldevice after they were pushed */ return_error(gs_error_undefined); dname = op->value.pdevice->dname; make_const_string(op, avm_foreign | a_readonly, strlen(dname), (const byte *)dname); return 0; }
none
8
1
int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; unsigned long i; struct kvm_memory_slot *memslot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* Disallow changing a memory slot's size. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; for (i = 0; i < KVM_MEMORY_SLOTS; ++i) { struct kvm_memory_slot *s = &kvm->memslots->memslots[i]; if (s == memslot || !s->npages) continue; if (!((base_gfn + npages <= s->base_gfn) || (base_gfn >= s->base_gfn + s->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* Allocate if a slot is being created */ if (npages && !old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted * memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); /* * If the new memory slot is created, we need to clear all * mmio sptes. */ if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT) kvm_arch_flush_shadow_all(kvm); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; }
CWE-399
4
1
void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; CameraInfo[0] = 0; CameraInfo[1] = 0; switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if(iCanonFocalType>=maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if(iCanonCurFocal>=maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if(iCanonLensID>=maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if(iCanonMinFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if(iCanonMaxFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if(iCanonLens+64>=maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; }
CWE-119
0
1
void MediaStreamDispatcherHost::DoOpenDevice( int32_t page_request_id, const std::string& device_id, blink::MediaStreamType type, OpenDeviceCallback callback, MediaDeviceSaltAndOrigin salt_and_origin) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!MediaStreamManager::IsOriginAllowed(render_process_id_, salt_and_origin.origin)) { std::move(callback).Run(false /* success */, std::string(), blink::MediaStreamDevice()); return; } media_stream_manager_->OpenDevice( render_process_id_, render_frame_id_, page_request_id, requester_id_, device_id, type, std::move(salt_and_origin), std::move(callback), base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped, weak_factory_.GetWeakPtr())); }
CWE-119
0
1
inline StreamWriteResult StreamBase::Write( uv_buf_t* bufs, size_t count, uv_stream_t* send_handle, v8::Local<v8::Object> req_wrap_obj) { Environment* env = stream_env(); int err; size_t total_bytes = 0; for (size_t i = 0; i < count; ++i) total_bytes += bufs[i].len; bytes_written_ += total_bytes; if (send_handle == nullptr) { err = DoTryWrite(&bufs, &count); if (err != 0 || count == 0) { return StreamWriteResult { false, err, nullptr, total_bytes }; } } HandleScope handle_scope(env->isolate()); if (req_wrap_obj.IsEmpty()) { req_wrap_obj = env->write_wrap_template() ->NewInstance(env->context()).ToLocalChecked(); StreamReq::ResetObject(req_wrap_obj); } AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(GetAsyncWrap()); WriteWrap* req_wrap = CreateWriteWrap(req_wrap_obj); err = DoWrite(req_wrap, bufs, count, send_handle); bool async = err == 0; if (!async) { req_wrap->Dispose(); req_wrap = nullptr; } const char* msg = Error(); if (msg != nullptr) { req_wrap_obj->Set(env->error_string(), OneByteString(env->isolate(), msg)); ClearError(); } return StreamWriteResult { async, err, req_wrap, total_bytes }; }
CWE-416
5
1
int wc_SignatureGenerateHash( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* hash_data, word32 hash_len, byte* sig, word32 *sig_len, const void* key, word32 key_len, WC_RNG* rng) { int ret; /* Suppress possible unused arg if all signature types are disabled */ (void)rng; /* Check arguments */ if (hash_data == NULL || hash_len <= 0 || sig == NULL || sig_len == NULL || *sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (needs to be at least max) */ if ((int)*sig_len < wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid hash type/len"); return ret; } ret = 0; /* Create signature using hash as data */ switch (sig_type) { case WC_SIGNATURE_TYPE_ECC: #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN) /* Create signature using provided ECC key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((ecc_key*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_ecc_sign_hash(hash_data, hash_len, sig, sig_len, rng, (ecc_key*)key); } while (ret == WC_PENDING_E); #else ret = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_RSA_W_ENC: case WC_SIGNATURE_TYPE_RSA: #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) /* Create signature using provided RSA key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((RsaKey*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_RsaSSL_Sign(hash_data, hash_len, sig, *sig_len, (RsaKey*)key, rng); } while (ret == WC_PENDING_E); if (ret >= 0) { *sig_len = ret; ret = 0; /* Success */ } #else ret = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_NONE: default: ret = BAD_FUNC_ARG; break; } return ret; }
CWE-200
3
1
void QuicClientPromisedInfo::OnPromiseHeaders(const SpdyHeaderBlock& headers) { SpdyHeaderBlock::const_iterator it = headers.find(kHttp2MethodHeader); DCHECK(it != headers.end()); if (!(it->second == "GET" || it->second == "HEAD")) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid method " << it->second; Reset(QUIC_INVALID_PROMISE_METHOD); return; } if (!SpdyUtils::UrlIsValid(headers)) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid URL " << url_; Reset(QUIC_INVALID_PROMISE_URL); return; } if (!session_->IsAuthorized(SpdyUtils::GetHostNameFromHeaderBlock(headers))) { Reset(QUIC_UNAUTHORIZED_PROMISE_URL); return; } request_headers_.reset(new SpdyHeaderBlock(headers.Clone())); }
CWE-119
0
1
_g_file_remove_directory (GFile *directory, GCancellable *cancellable, GError **error) { GFileEnumerator *enumerator; GFileInfo *info; gboolean error_occurred = FALSE; if (directory == NULL) return TRUE; enumerator = g_file_enumerate_children (directory, G_FILE_ATTRIBUTE_STANDARD_NAME "," G_FILE_ATTRIBUTE_STANDARD_TYPE, 0, cancellable, error); while (! error_occurred && (info = g_file_enumerator_next_file (enumerator, cancellable, error)) != NULL) { GFile *child; child = g_file_get_child (directory, g_file_info_get_name (info)); switch (g_file_info_get_file_type (info)) { case G_FILE_TYPE_DIRECTORY: if (! _g_file_remove_directory (child, cancellable, error)) error_occurred = TRUE; break; default: if (! g_file_delete (child, cancellable, error)) error_occurred = TRUE; break; } g_object_unref (child); g_object_unref (info); } if (! error_occurred && ! g_file_delete (directory, cancellable, error)) error_occurred = TRUE; g_object_unref (enumerator); return ! error_occurred; }
CWE-20
2
1
do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags, size_t size, int clazz) { #ifdef ELFCORE int os_style = -1; /* * Sigh. The 2.0.36 kernel in Debian 2.1, at * least, doesn't correctly implement name * sections, in core dumps, as specified by * the "Program Linking" section of "UNIX(R) System * V Release 4 Programmer's Guide: ANSI C and * Programming Support Tools", because my copy * clearly says "The first 'namesz' bytes in 'name' * contain a *null-terminated* [emphasis mine] * character representation of the entry's owner * or originator", but the 2.0.36 kernel code * doesn't include the terminating null in the * name.... */ if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) || (namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) { os_style = OS_STYLE_SVR4; } if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) { os_style = OS_STYLE_FREEBSD; } if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11) == 0)) { os_style = OS_STYLE_NETBSD; } if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { if (file_printf(ms, ", %s-style", os_style_names[os_style]) == -1) return 1; *flags |= FLAGS_DID_CORE_STYLE; *flags |= os_style; } switch (os_style) { case OS_STYLE_NETBSD: if (type == NT_NETBSD_CORE_PROCINFO) { char sbuf[512]; struct NetBSD_elfcore_procinfo pi; memset(&pi, 0, sizeof(pi)); memcpy(&pi, nbuf + doff, descsz); if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, " "gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)", file_printable(sbuf, sizeof(sbuf), CAST(char *, pi.cpi_name)), elf_getu32(swap, (uint32_t)pi.cpi_pid), elf_getu32(swap, pi.cpi_euid), elf_getu32(swap, pi.cpi_egid), elf_getu32(swap, pi.cpi_nlwps), elf_getu32(swap, (uint32_t)pi.cpi_siglwp), elf_getu32(swap, pi.cpi_signo), elf_getu32(swap, pi.cpi_sigcode)) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; } break; default: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t i, j; unsigned char c; /* * Extract the program name. We assume * it to be 16 characters (that's what it * is in SunOS 5.x and Linux). * * Unfortunately, it's at a different offset * in various OSes, so try multiple offsets. * If the characters aren't all printable, * reject it. */ for (i = 0; i < NOFFSETS; i++) { unsigned char *cname, *cp; size_t reloffset = prpsoffsets(i); size_t noffset = doff + reloffset; size_t k; for (j = 0; j < 16; j++, noffset++, reloffset++) { /* * Make sure we're not past * the end of the buffer; if * we are, just give up. */ if (noffset >= size) goto tryanother; /* * Make sure we're not past * the end of the contents; * if we are, this obviously * isn't the right offset. */ if (reloffset >= descsz) goto tryanother; c = nbuf[noffset]; if (c == '\0') { /* * A '\0' at the * beginning is * obviously wrong. * Any other '\0' * means we're done. */ if (j == 0) goto tryanother; else break; } else { /* * A nonprintable * character is also * wrong. */ if (!isprint(c) || isquote(c)) goto tryanother; } } /* * Well, that worked. */ /* * Try next offsets, in case this match is * in the middle of a string. */ for (k = i + 1 ; k < NOFFSETS; k++) { size_t no; int adjust = 1; if (prpsoffsets(k) >= prpsoffsets(i)) continue; for (no = doff + prpsoffsets(k); no < doff + prpsoffsets(i); no++) adjust = adjust && isprint(nbuf[no]); if (adjust) i = k; } cname = (unsigned char *) &nbuf[doff + prpsoffsets(i)]; for (cp = cname; *cp && isprint(*cp); cp++) continue; /* * Linux apparently appends a space at the end * of the command line: remove it. */ while (cp > cname && isspace(cp[-1])) cp--; if (file_printf(ms, ", from '%.*s'", (int)(cp - cname), cname) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; tryanother: ; } } break; } #endif return 0; }
CWE-125
1
1
static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { ut8 *end, *need = NULL; const char *section_name = ""; Elf_(Shdr) *link_shdr = NULL; const char *link_section_name = ""; Sdb *sdb_vernaux = NULL; Sdb *sdb_version = NULL; Sdb *sdb = NULL; int i, cnt; if (!bin || !bin->dynstr) { return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { return NULL; } if (shdr->sh_size < 1) { return NULL; } sdb = sdb_new0 (); if (!sdb) { return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) { bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n"); goto beach; } end = need + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "num_entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) { goto beach; } if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) { goto beach; } i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size); if (i < 0) goto beach; //XXX we should use DT_VERNEEDNUM instead of sh_info //TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) { int j, isum; ut8 *vstart = need + i; Elf_(Verneed) vvn = {0}; if (vstart + sizeof (Elf_(Verneed)) > end) { goto beach; } Elf_(Verneed) *entry = &vvn; char key[32] = {0}; sdb_version = sdb_new0 (); if (!sdb_version) { goto beach; } j = 0; vvn.vn_version = READ16 (vstart, j) vvn.vn_cnt = READ16 (vstart, j) vvn.vn_file = READ32 (vstart, j) vvn.vn_aux = READ32 (vstart, j) vvn.vn_next = READ32 (vstart, j) sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0); sdb_num_set (sdb_version, "idx", i, 0); if (entry->vn_file > bin->dynstr_size) { goto beach; } { char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16); sdb_set (sdb_version, "file_name", s, 0); free (s); } sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0); vstart += entry->vn_aux; for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) { int k; Elf_(Vernaux) * aux = NULL; Elf_(Vernaux) vaux = {0}; sdb_vernaux = sdb_new0 (); if (!sdb_vernaux) { goto beach; } aux = (Elf_(Vernaux)*)&vaux; k = 0; vaux.vna_hash = READ32 (vstart, k) vaux.vna_flags = READ16 (vstart, k) vaux.vna_other = READ16 (vstart, k) vaux.vna_name = READ32 (vstart, k) vaux.vna_next = READ32 (vstart, k) if (aux->vna_name > bin->dynstr_size) { goto beach; } sdb_num_set (sdb_vernaux, "idx", isum, 0); if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) { char name [16]; strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1); name[sizeof(name)-1] = 0; sdb_set (sdb_vernaux, "name", name, 0); } sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0); sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0); isum += aux->vna_next; vstart += aux->vna_next; snprintf (key, sizeof (key), "vernaux%d", j); sdb_ns_set (sdb_version, key, sdb_vernaux); } if ((int)entry->vn_next < 0) { bprintf ("Invalid vn_next\n"); break; } i += entry->vn_next; snprintf (key, sizeof (key), "version%d", cnt ); sdb_ns_set (sdb, key, sdb_version); //if entry->vn_next is 0 it iterate infinitely if (!entry->vn_next) { break; } } free (need); return sdb; beach: free (need); sdb_free (sdb_vernaux); sdb_free (sdb_version); sdb_free (sdb); return NULL; }
CWE-125
1
1
unsigned long X509_issuer_and_serial_hash(X509 *a) { unsigned long ret = 0; EVP_MD_CTX *ctx = EVP_MD_CTX_new(); unsigned char md[16]; char *f; if (ctx == NULL) goto err; f = X509_NAME_oneline(a->cert_info.issuer, NULL, 0); if (!EVP_DigestInit_ex(ctx, EVP_md5(), NULL)) goto err; if (!EVP_DigestUpdate(ctx, (unsigned char *)f, strlen(f))) goto err; OPENSSL_free(f); if (!EVP_DigestUpdate (ctx, (unsigned char *)a->cert_info.serialNumber.data, (unsigned long)a->cert_info.serialNumber.length)) goto err; if (!EVP_DigestFinal_ex(ctx, &(md[0]), NULL)) goto err; ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) | ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L) ) & 0xffffffffL; err: EVP_MD_CTX_free(ctx); return ret; }
CWE-476
6
1
PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s) { static const char module[] = "PixarLogDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t i; tmsize_t nsamples; int llen; uint16 *up; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: nsamples = occ / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: nsamples = occ; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; (void) s; assert(sp != NULL); sp->stream.next_out = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16)); if (sp->stream.avail_out != nsamples * sizeof(uint16)) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } do { int state = inflate(&sp->stream, Z_PARTIAL_FLUSH); if (state == Z_STREAM_END) { break; /* XXX */ } if (state == Z_DATA_ERROR) { TIFFErrorExt(tif->tif_clientdata, module, "Decoding error at scanline %lu, %s", (unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)"); if (inflateSync(&sp->stream) != Z_OK) return (0); continue; } if (state != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (sp->stream.avail_out > 0); /* hopefully, we got all the bytes we needed */ if (sp->stream.avail_out != 0) { TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)", (unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out); return (0); } up = sp->tbuf; /* Swap bytes in the data if from a different endian machine. */ if (tif->tif_flags & TIFF_SWAB) TIFFSwabArrayOfShort(up, nsamples); /* * if llen is not an exact multiple of nsamples, the decode operation * may overflow the output buffer, so truncate it enough to prevent * that but still salvage as much data as possible. */ if (nsamples % llen) { TIFFWarningExt(tif->tif_clientdata, module, "stride %lu is not a multiple of sample count, " "%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples); nsamples -= nsamples % llen; } for (i = 0; i < nsamples; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalAccumulateF(up, llen, sp->stride, (float *)op, sp->ToLinearF); op += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalAccumulate16(up, llen, sp->stride, (uint16 *)op, sp->ToLinear16); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_12BITPICIO: horizontalAccumulate12(up, llen, sp->stride, (int16 *)op, sp->ToLinearF); op += llen * sizeof(int16); break; case PIXARLOGDATAFMT_11BITLOG: horizontalAccumulate11(up, llen, sp->stride, (uint16 *)op); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalAccumulate8(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; case PIXARLOGDATAFMT_8BITABGR: horizontalAccumulate8abgr(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "Unsupported bits/sample: %d", td->td_bitspersample); return (0); } } return (1); }
CWE-787
7
0
int ssl3_shutdown(SSL *s) { int ret; /* Don't do anything much if we have not done the handshake or * we don't want to send messages :-) */ if ((s->quiet_shutdown) || (s->state == SSL_ST_BEFORE)) { s->shutdown=(SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN); return(1); } if (!(s->shutdown & SSL_SENT_SHUTDOWN)) { s->shutdown|=SSL_SENT_SHUTDOWN; #if 1 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_CLOSE_NOTIFY); #endif /* our shutdown alert has been sent now, and if it still needs * to be written, s->s3->alert_dispatch will be true */ if (s->s3->alert_dispatch) return(-1); /* return WANT_WRITE */ } else if (s->s3->alert_dispatch) { /* resend it if not sent */ #if 1 ret=s->method->ssl_dispatch_alert(s); if(ret == -1) { /* we only get to return -1 here the 2nd/Nth * invocation, we must have already signalled * return 0 upon a previous invoation, * return WANT_WRITE */ return(ret); } #endif } else if (!(s->shutdown & SSL_RECEIVED_SHUTDOWN)) { /* If we are waiting for a close from our peer, we are closed */ s->method->ssl_read_bytes(s,0,NULL,0,0); if(!(s->shutdown & SSL_RECEIVED_SHUTDOWN)) { return(-1); /* return WANT_READ */ } } if ((s->shutdown == (SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN)) && !s->s3->alert_dispatch) return(1); else return(0); }
none
8
1
static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status, cubemap = MagickFalse, volume = MagickFalse, matte; CompressionType compression; DDSInfo dds_info; DDSDecoder *decoder; size_t n, num_images; /* 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 image structure. */ if (ReadDDSInfo(image, &dds_info) != MagickTrue) { ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP) cubemap = MagickTrue; if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0) volume = MagickTrue; (void) SeekBlob(image, 128, SEEK_SET); /* Determine pixel format */ if (dds_info.pixelformat.flags & DDPF_RGB) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { matte = MagickTrue; decoder = ReadUncompressedRGBA; } else { matte = MagickTrue; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_LUMINANCE) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { /* Not sure how to handle this */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } else { matte = MagickFalse; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_FOURCC) { switch (dds_info.pixelformat.fourcc) { case FOURCC_DXT1: { matte = MagickFalse; compression = DXT1Compression; decoder = ReadDXT1; break; } case FOURCC_DXT3: { matte = MagickTrue; compression = DXT3Compression; decoder = ReadDXT3; break; } case FOURCC_DXT5: { matte = MagickTrue; compression = DXT5Compression; decoder = ReadDXT5; break; } default: { /* Unknown FOURCC */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } } } else { /* Neither compressed nor uncompressed... thus unsupported */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } num_images = 1; if (cubemap) { /* Determine number of faces defined in the cubemap */ num_images = 0; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++; } if (volume) num_images = dds_info.depth; for (n = 0; n < num_images; n++) { if (n != 0) { /* Start a new image */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } image->matte = matte; image->compression = compression; image->columns = dds_info.width; image->rows = dds_info.height; image->storage_class = DirectClass; image->endian = LSBEndian; image->depth = 8; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((decoder)(image, &dds_info, exception) != MagickTrue) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
CWE-20
2
1
HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env) { char *p, *q, *r; int i, w, x, y, z, count, width; struct readbuffer *obuf = h_env->obuf; struct environment *envs = h_env->envs; Str tmp; int hseq; int cmd; #ifdef ID_EXT char *id = NULL; #endif /* ID_EXT */ cmd = tag->tagid; if (obuf->flag & RB_PRE) { switch (cmd) { case HTML_NOBR: case HTML_N_NOBR: case HTML_PRE_INT: case HTML_N_PRE_INT: return 1; } } switch (cmd) { case HTML_B: obuf->in_bold++; if (obuf->in_bold > 1) return 1; return 0; case HTML_N_B: if (obuf->in_bold == 1 && close_effect0(obuf, HTML_B)) obuf->in_bold = 0; if (obuf->in_bold > 0) { obuf->in_bold--; if (obuf->in_bold == 0) return 0; } return 1; case HTML_I: obuf->in_italic++; if (obuf->in_italic > 1) return 1; return 0; case HTML_N_I: if (obuf->in_italic == 1 && close_effect0(obuf, HTML_I)) obuf->in_italic = 0; if (obuf->in_italic > 0) { obuf->in_italic--; if (obuf->in_italic == 0) return 0; } return 1; case HTML_U: obuf->in_under++; if (obuf->in_under > 1) return 1; return 0; case HTML_N_U: if (obuf->in_under == 1 && close_effect0(obuf, HTML_U)) obuf->in_under = 0; if (obuf->in_under > 0) { obuf->in_under--; if (obuf->in_under == 0) return 0; } return 1; case HTML_EM: HTMLlineproc1("<i>", h_env); return 1; case HTML_N_EM: HTMLlineproc1("</i>", h_env); return 1; case HTML_STRONG: HTMLlineproc1("<b>", h_env); return 1; case HTML_N_STRONG: HTMLlineproc1("</b>", h_env); return 1; case HTML_Q: HTMLlineproc1("`", h_env); return 1; case HTML_N_Q: HTMLlineproc1("'", h_env); return 1; case HTML_P: case HTML_N_P: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; if (cmd == HTML_P) { set_alignment(obuf, tag); obuf->flag |= RB_P; } return 1; case HTML_BR: flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); h_env->blank_lines = 0; return 1; case HTML_H: if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } HTMLlineproc1("<b>", h_env); set_alignment(obuf, tag); return 1; case HTML_N_H: HTMLlineproc1("</b>", h_env); if (!(obuf->flag & RB_PREMODE)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); close_anchor(h_env, obuf); obuf->flag |= RB_IGNORE_P; return 1; case HTML_UL: case HTML_OL: case HTML_BLQ: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_BLQ)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (cmd == HTML_UL || cmd == HTML_OL) { if (parsedtag_get_value(tag, ATTR_START, &count)) { envs[h_env->envc].count = count - 1; } } if (cmd == HTML_OL) { envs[h_env->envc].type = '1'; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { envs[h_env->envc].type = (int)*p; } } if (cmd == HTML_UL) envs[h_env->envc].type = ul_type(tag, 0); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 1; case HTML_N_UL: case HTML_N_OL: case HTML_N_DL: case HTML_N_BLQ: CLOSE_DT; CLOSE_A; if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); POP_ENV; if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_N_DL || cmd == HTML_N_BLQ)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, INDENT_INCR, h_env->limit); obuf->flag |= RB_IGNORE_P; } } close_anchor(h_env, obuf); return 1; case HTML_DL: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (parsedtag_exists(tag, ATTR_COMPACT)) envs[h_env->envc].env = HTML_DL_COMPACT; obuf->flag |= RB_IGNORE_P; return 1; case HTML_LI: CLOSE_A; CLOSE_DT; if (h_env->envc > 0) { Str num; flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); envs[h_env->envc].count++; if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { count = atoi(p); if (count > 0) envs[h_env->envc].count = count; else envs[h_env->envc].count = 0; } switch (envs[h_env->envc].env) { case HTML_UL: envs[h_env->envc].type = ul_type(tag, envs[h_env->envc].type); for (i = 0; i < INDENT_INCR - 3; i++) push_charp(obuf, 1, NBSP, PC_ASCII); tmp = Strnew(); switch (envs[h_env->envc].type) { case 'd': push_symbol(tmp, UL_SYMBOL_DISC, symbol_width, 1); break; case 'c': push_symbol(tmp, UL_SYMBOL_CIRCLE, symbol_width, 1); break; case 's': push_symbol(tmp, UL_SYMBOL_SQUARE, symbol_width, 1); break; default: push_symbol(tmp, UL_SYMBOL((h_env->envc_real - 1) % MAX_UL_LEVEL), symbol_width, 1); break; } if (symbol_width == 1) push_charp(obuf, 1, NBSP, PC_ASCII); push_str(obuf, symbol_width, tmp, PC_ASCII); push_charp(obuf, 1, NBSP, PC_ASCII); set_space_to_prevchar(obuf->prevchar); break; case HTML_OL: if (parsedtag_get_value(tag, ATTR_TYPE, &p)) envs[h_env->envc].type = (int)*p; switch ((envs[h_env->envc].count > 0)? envs[h_env->envc].type: '1') { case 'i': num = romanNumeral(envs[h_env->envc].count); break; case 'I': num = romanNumeral(envs[h_env->envc].count); Strupper(num); break; case 'a': num = romanAlphabet(envs[h_env->envc].count); break; case 'A': num = romanAlphabet(envs[h_env->envc].count); Strupper(num); break; default: num = Sprintf("%d", envs[h_env->envc].count); break; } if (INDENT_INCR >= 4) Strcat_charp(num, ". "); else Strcat_char(num, '.'); push_spaces(obuf, 1, INDENT_INCR - num->length); push_str(obuf, num->length, num, PC_ASCII); if (INDENT_INCR >= 4) set_space_to_prevchar(obuf->prevchar); break; default: push_spaces(obuf, 1, INDENT_INCR); break; } } else { flushline(h_env, obuf, 0, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DT: CLOSE_A; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); } if (!(obuf->flag & RB_IN_DT)) { HTMLlineproc1("<b>", h_env); obuf->flag |= RB_IN_DT; } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DD: CLOSE_A; CLOSE_DT; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (envs[h_env->envc].env == HTML_DL_COMPACT) { if (obuf->pos > envs[h_env->envc].indent) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); else push_spaces(obuf, 1, envs[h_env->envc].indent - obuf->pos); } else flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); /* obuf->flag |= RB_IGNORE_P; */ return 1; case HTML_TITLE: close_anchor(h_env, obuf); process_title(tag); obuf->flag |= RB_TITLE; obuf->end_tag = HTML_N_TITLE; return 1; case HTML_N_TITLE: if (!(obuf->flag & RB_TITLE)) return 1; obuf->flag &= ~RB_TITLE; obuf->end_tag = 0; tmp = process_n_title(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_TITLE_ALT: if (parsedtag_get_value(tag, ATTR_TITLE, &p)) h_env->title = html_unquote(p); return 0; case HTML_FRAMESET: PUSH_ENV(cmd); push_charp(obuf, 9, "--FRAME--", PC_ASCII); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_N_FRAMESET: if (h_env->envc > 0) { POP_ENV; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } return 0; case HTML_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= (RB_NOFRAMES | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag &= ~RB_NOFRAMES; return 1; case HTML_FRAME: q = r = NULL; parsedtag_get_value(tag, ATTR_SRC, &q); parsedtag_get_value(tag, ATTR_NAME, &r); if (q) { q = html_quote(q); push_tag(obuf, Sprintf("<a hseq=\"%d\" href=\"%s\">", cur_hseq++, q)->ptr, HTML_A); if (r) q = html_quote(r); push_charp(obuf, get_strwidth(q), q, PC_ASCII); push_tag(obuf, "</a>", HTML_N_A); } flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_HR: close_anchor(h_env, obuf); tmp = process_hr(tag, h_env->limit, envs[h_env->envc].indent); HTMLlineproc1(tmp->ptr, h_env); set_space_to_prevchar(obuf->prevchar); return 1; case HTML_PRE: x = parsedtag_exists(tag, ATTR_FOR_TABLE); CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!x) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } else fillline(obuf, envs[h_env->envc].indent); obuf->flag |= (RB_PRE | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_PRE: flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_IGNORE_P)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; h_env->blank_lines++; } obuf->flag &= ~RB_PRE; close_anchor(h_env, obuf); return 1; case HTML_PRE_INT: i = obuf->line->length; append_tags(obuf); if (!(obuf->flag & RB_SPECIAL)) { set_breakpoint(obuf, obuf->line->length - i); } obuf->flag |= RB_PRE_INT; return 0; case HTML_N_PRE_INT: push_tag(obuf, "</pre_int>", HTML_N_PRE_INT); obuf->flag &= ~RB_PRE_INT; if (!(obuf->flag & RB_SPECIAL) && obuf->pos > obuf->bp.pos) { set_prevchar(obuf->prevchar, "", 0); obuf->prev_ctype = PC_CTRL; } return 1; case HTML_NOBR: obuf->flag |= RB_NOBR; obuf->nobr_level++; return 0; case HTML_N_NOBR: if (obuf->nobr_level > 0) obuf->nobr_level--; if (obuf->nobr_level == 0) obuf->flag &= ~RB_NOBR; return 0; case HTML_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PRE | RB_IGNORE_P); return 1; case HTML_N_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PRE; return 1; case HTML_LISTING: case HTML_XMP: case HTML_PLAINTEXT: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PLAIN | RB_IGNORE_P); switch (cmd) { case HTML_LISTING: obuf->end_tag = HTML_N_LISTING; break; case HTML_XMP: obuf->end_tag = HTML_N_XMP; break; case HTML_PLAINTEXT: obuf->end_tag = MAX_HTMLTAG; break; } return 1; case HTML_N_LISTING: case HTML_N_XMP: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PLAIN; obuf->end_tag = 0; return 1; case HTML_SCRIPT: obuf->flag |= RB_SCRIPT; obuf->end_tag = HTML_N_SCRIPT; return 1; case HTML_STYLE: obuf->flag |= RB_STYLE; obuf->end_tag = HTML_N_STYLE; return 1; case HTML_N_SCRIPT: obuf->flag &= ~RB_SCRIPT; obuf->end_tag = 0; return 1; case HTML_N_STYLE: obuf->flag &= ~RB_STYLE; obuf->end_tag = 0; return 1; case HTML_A: if (obuf->anchor.url) close_anchor(h_env, obuf); hseq = 0; if (parsedtag_get_value(tag, ATTR_HREF, &p)) obuf->anchor.url = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TARGET, &p)) obuf->anchor.target = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_REFERER, &p)) obuf->anchor.referer = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TITLE, &p)) obuf->anchor.title = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_ACCESSKEY, &p)) obuf->anchor.accesskey = (unsigned char)*p; if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) obuf->anchor.hseq = hseq; if (hseq == 0 && obuf->anchor.url) { obuf->anchor.hseq = cur_hseq; tmp = process_anchor(tag, h_env->tagbuf->ptr); push_tag(obuf, tmp->ptr, HTML_A); if (displayLinkNumber) HTMLlineproc1(getLinkNumberStr(-1)->ptr, h_env); return 1; } return 0; case HTML_N_A: close_anchor(h_env, obuf); return 1; case HTML_IMG: tmp = process_img(tag, h_env->limit); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_IMG_ALT: if (parsedtag_get_value(tag, ATTR_SRC, &p)) obuf->img_alt = Strnew_charp(p); #ifdef USE_IMAGE i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } #endif return 0; case HTML_N_IMG_ALT: if (obuf->img_alt) { if (!close_effect0(obuf, HTML_IMG_ALT)) push_tag(obuf, "</img_alt>", HTML_N_IMG_ALT); obuf->img_alt = NULL; } return 1; case HTML_INPUT_ALT: i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) { obuf->input_alt.hseq = hseq; } if (parsedtag_get_value(tag, ATTR_FID, &i)) { obuf->input_alt.fid = i; } if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { obuf->input_alt.type = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { obuf->input_alt.value = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_NAME, &p)) { obuf->input_alt.name = Strnew_charp(p); } obuf->input_alt.in = 1; return 0; case HTML_N_INPUT_ALT: if (obuf->input_alt.in) { if (!close_effect0(obuf, HTML_INPUT_ALT)) push_tag(obuf, "</input_alt>", HTML_N_INPUT_ALT); obuf->input_alt.hseq = 0; obuf->input_alt.fid = -1; obuf->input_alt.in = 0; obuf->input_alt.type = NULL; obuf->input_alt.name = NULL; obuf->input_alt.value = NULL; } return 1; case HTML_TABLE: close_anchor(h_env, obuf); obuf->table_level++; if (obuf->table_level >= MAX_TABLE) break; w = BORDER_NONE; /* x: cellspacing, y: cellpadding */ x = 2; y = 1; z = 0; width = 0; if (parsedtag_exists(tag, ATTR_BORDER)) { if (parsedtag_get_value(tag, ATTR_BORDER, &w)) { if (w > 2) w = BORDER_THICK; else if (w < 0) { /* weird */ w = BORDER_THIN; } } else w = BORDER_THIN; } if (DisplayBorders && w == BORDER_NONE) w = BORDER_THIN; if (parsedtag_get_value(tag, ATTR_WIDTH, &i)) { if (obuf->table_level == 0) width = REAL_WIDTH(i, h_env->limit - envs[h_env->envc].indent); else width = RELATIVE_WIDTH(i); } if (parsedtag_exists(tag, ATTR_HBORDER)) w = BORDER_NOWIN; #define MAX_CELLSPACING 1000 #define MAX_CELLPADDING 1000 #define MAX_VSPACE 1000 parsedtag_get_value(tag, ATTR_CELLSPACING, &x); parsedtag_get_value(tag, ATTR_CELLPADDING, &y); parsedtag_get_value(tag, ATTR_VSPACE, &z); if (x > MAX_CELLSPACING) x = MAX_CELLSPACING; if (y > MAX_CELLPADDING) y = MAX_CELLPADDING; if (z > MAX_VSPACE) z = MAX_VSPACE; #ifdef ID_EXT parsedtag_get_value(tag, ATTR_ID, &id); #endif /* ID_EXT */ tables[obuf->table_level] = begin_table(w, x, y, z); #ifdef ID_EXT if (id != NULL) tables[obuf->table_level]->id = Strnew_charp(id); #endif /* ID_EXT */ table_mode[obuf->table_level].pre_mode = 0; table_mode[obuf->table_level].indent_level = 0; table_mode[obuf->table_level].nobr_level = 0; table_mode[obuf->table_level].caption = 0; table_mode[obuf->table_level].end_tag = 0; /* HTML_UNKNOWN */ #ifndef TABLE_EXPAND tables[obuf->table_level]->total_width = width; #else tables[obuf->table_level]->real_width = width; tables[obuf->table_level]->total_width = 0; #endif return 1; case HTML_N_TABLE: /* should be processed in HTMLlineproc() */ return 1; case HTML_CENTER: CLOSE_A; if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_SAVE_FLAG(obuf); RB_SET_ALIGN(obuf, RB_CENTER); return 1; case HTML_N_CENTER: CLOSE_A; if (!(obuf->flag & RB_PREMODE)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV_INT: CLOSE_P; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV_INT: CLOSE_P; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_FORM: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); tmp = process_form(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_FORM: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; process_n_form(); return 1; case HTML_INPUT: close_anchor(h_env, obuf); tmp = process_input(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_BUTTON: tmp = process_button(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_BUTTON: tmp = process_n_button(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_SELECT: close_anchor(h_env, obuf); tmp = process_select(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INSELECT; obuf->end_tag = HTML_N_SELECT; return 1; case HTML_N_SELECT: obuf->flag &= ~RB_INSELECT; obuf->end_tag = 0; tmp = process_n_select(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_OPTION: /* nothing */ return 1; case HTML_TEXTAREA: close_anchor(h_env, obuf); tmp = process_textarea(tag, h_env->limit); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INTXTA; obuf->end_tag = HTML_N_TEXTAREA; return 1; case HTML_N_TEXTAREA: obuf->flag &= ~RB_INTXTA; obuf->end_tag = 0; tmp = process_n_textarea(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_ISINDEX: p = ""; q = "!CURRENT_URL!"; parsedtag_get_value(tag, ATTR_PROMPT, &p); parsedtag_get_value(tag, ATTR_ACTION, &q); tmp = Strnew_m_charp("<form method=get action=\"", html_quote(q), "\">", html_quote(p), "<input type=text name=\"\" accept></form>", NULL); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_META: p = q = r = NULL; parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &p); parsedtag_get_value(tag, ATTR_CONTENT, &q); #ifdef USE_M17N parsedtag_get_value(tag, ATTR_CHARSET, &r); if (r) { /* <meta charset=""> */ SKIP_BLANKS(r); meta_charset = wc_guess_charset(r, 0); } else if (p && q && !strcasecmp(p, "Content-Type") && (q = strcasestr(q, "charset")) != NULL) { q += 7; SKIP_BLANKS(q); if (*q == '=') { q++; SKIP_BLANKS(q); meta_charset = wc_guess_charset(q, 0); } } else #endif if (p && q && !strcasecmp(p, "refresh")) { int refresh_interval; tmp = NULL; refresh_interval = getMetaRefreshParam(q, &tmp); if (tmp) { q = html_quote(tmp->ptr); tmp = Sprintf("Refresh (%d sec) <a href=\"%s\">%s</a>", refresh_interval, q, q); } else if (refresh_interval > 0) tmp = Sprintf("Refresh (%d sec)", refresh_interval); if (tmp) { HTMLlineproc1(tmp->ptr, h_env); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!is_redisplay && !((obuf->flag & RB_NOFRAMES) && RenderFrame)) { tag->need_reconstruct = TRUE; return 0; } } } return 1; case HTML_BASE: #if defined(USE_M17N) || defined(USE_IMAGE) p = NULL; if (parsedtag_get_value(tag, ATTR_HREF, &p)) { cur_baseURL = New(ParsedURL); parseURL(p, cur_baseURL, NULL); } #endif case HTML_MAP: case HTML_N_MAP: case HTML_AREA: return 0; case HTML_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[DEL:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:DEL]</U>", h_env); case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } break; } return 1; case HTML_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[S:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:S]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } } return 1; case HTML_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[INS:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_ins++; if (obuf->in_ins == 1) { push_tag(obuf, "<ins>", HTML_INS); } break; } return 1; case HTML_N_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:INS]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_ins == 0) return 1; if (obuf->in_ins == 1 && close_effect0(obuf, HTML_INS)) obuf->in_ins = 0; if (obuf->in_ins > 0) { obuf->in_ins--; if (obuf->in_ins == 0) { push_tag(obuf, "</ins>", HTML_N_INS); } } break; } return 1; case HTML_SUP: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("^", h_env); return 1; case HTML_N_SUP: return 1; case HTML_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("[", h_env); return 1; case HTML_N_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("]", h_env); return 1; case HTML_FONT: case HTML_N_FONT: case HTML_NOP: return 1; case HTML_BGSOUND: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">bgsound(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_EMBED: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">embed(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_APPLET: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_ARCHIVE, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">applet archive(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_BODY: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_BACKGROUND, &p)) { Str s; q = html_quote(p); s = Sprintf("<IMG SRC=\"%s\" ALT=\"bg image(%s)\"><BR>", q, q); HTMLlineproc1(s->ptr, h_env); } } case HTML_N_HEAD: if (obuf->flag & RB_TITLE) HTMLlineproc1("</title>", h_env); case HTML_HEAD: case HTML_N_BODY: return 1; default: /* obuf->prevchar = '\0'; */ return 0; } /* not reached */ return 0; }
CWE-476
6
1
static MagickBooleanType WritePSImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define WriteRunlengthPacket(image,pixel,length,p) \ { \ if ((image->alpha_trait != UndefinedPixelTrait) && (length != 0) && \ (GetPixelAlpha(image,p) == (Quantum) TransparentAlpha)) \ { \ q=PopHexPixel(hex_digits,0xff,q); \ q=PopHexPixel(hex_digits,0xff,q); \ q=PopHexPixel(hex_digits,0xff,q); \ } \ else \ { \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.red)),q); \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.green)),q); \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(ClampToQuantum(pixel.blue)),q); \ } \ q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); \ } static const char *const hex_digits[] = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF", (const char *) NULL }, *const PostscriptProlog[]= { "%%BeginProlog", "%", "% Display a color image. The image is displayed in color on", "% Postscript viewers or printers that support color, otherwise", "% it is displayed as grayscale.", "%", "/DirectClassPacket", "{", " %", " % Get a DirectClass packet.", " %", " % Parameters:", " % red.", " % green.", " % blue.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile color_packet readhexstring pop pop", " compression 0 eq", " {", " /number_pixels 3 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add 3 mul def", " } ifelse", " 0 3 number_pixels 1 sub", " {", " pixels exch color_packet putinterval", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/DirectClassImage", "{", " %", " % Display a DirectClass image.", " %", " systemdict /colorimage known", " {", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { DirectClassPacket } false 3 colorimage", " }", " {", " %", " % No colorimage operator; convert to grayscale.", " %", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { GrayDirectClassPacket } image", " } ifelse", "} bind def", "", "/GrayDirectClassPacket", "{", " %", " % Get a DirectClass packet; convert to grayscale.", " %", " % Parameters:", " % red", " % green", " % blue", " % length: number of pixels minus one of this color (optional).", " %", " currentfile color_packet readhexstring pop pop", " color_packet 0 get 0.299 mul", " color_packet 1 get 0.587 mul add", " color_packet 2 get 0.114 mul add", " cvi", " /gray_packet exch def", " compression 0 eq", " {", " /number_pixels 1 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add def", " } ifelse", " 0 1 number_pixels 1 sub", " {", " pixels exch gray_packet put", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/GrayPseudoClassPacket", "{", " %", " % Get a PseudoClass packet; convert to grayscale.", " %", " % Parameters:", " % index: index into the colormap.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile byte readhexstring pop 0 get", " /offset exch 3 mul def", " /color_packet colormap offset 3 getinterval def", " color_packet 0 get 0.299 mul", " color_packet 1 get 0.587 mul add", " color_packet 2 get 0.114 mul add", " cvi", " /gray_packet exch def", " compression 0 eq", " {", " /number_pixels 1 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add def", " } ifelse", " 0 1 number_pixels 1 sub", " {", " pixels exch gray_packet put", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/PseudoClassPacket", "{", " %", " % Get a PseudoClass packet.", " %", " % Parameters:", " % index: index into the colormap.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile byte readhexstring pop 0 get", " /offset exch 3 mul def", " /color_packet colormap offset 3 getinterval def", " compression 0 eq", " {", " /number_pixels 3 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add 3 mul def", " } ifelse", " 0 3 number_pixels 1 sub", " {", " pixels exch color_packet putinterval", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/PseudoClassImage", "{", " %", " % Display a PseudoClass image.", " %", " % Parameters:", " % class: 0-PseudoClass or 1-Grayscale.", " %", " currentfile buffer readline pop", " token pop /class exch def pop", " class 0 gt", " {", " currentfile buffer readline pop", " token pop /depth exch def pop", " /grays columns 8 add depth sub depth mul 8 idiv string def", " columns rows depth", " [", " columns 0 0", " rows neg 0 rows", " ]", " { currentfile grays readhexstring pop } image", " }", " {", " %", " % Parameters:", " % colors: number of colors in the colormap.", " % colormap: red, green, blue color packets.", " %", " currentfile buffer readline pop", " token pop /colors exch def pop", " /colors colors 3 mul def", " /colormap colors string def", " currentfile colormap readhexstring pop pop", " systemdict /colorimage known", " {", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { PseudoClassPacket } false 3 colorimage", " }", " {", " %", " % No colorimage operator; convert to grayscale.", " %", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { GrayPseudoClassPacket } image", " } ifelse", " } ifelse", "} bind def", "", "/DisplayImage", "{", " %", " % Display a DirectClass or PseudoClass image.", " %", " % Parameters:", " % x & y translation.", " % x & y scale.", " % label pointsize.", " % image label.", " % image columns & rows.", " % class: 0-DirectClass or 1-PseudoClass.", " % compression: 0-none or 1-RunlengthEncoded.", " % hex color packets.", " %", " gsave", " /buffer 512 string def", " /byte 1 string def", " /color_packet 3 string def", " /pixels 768 string def", "", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " x y translate", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " currentfile buffer readline pop", " token pop /pointsize exch def pop", (const char *) NULL }, *const PostscriptEpilog[]= { " x y scale", " currentfile buffer readline pop", " token pop /columns exch def", " token pop /rows exch def pop", " currentfile buffer readline pop", " token pop /class exch def pop", " currentfile buffer readline pop", " token pop /compression exch def pop", " class 0 gt { PseudoClassImage } { DirectClassImage } ifelse", " grestore", (const char *) NULL }; char buffer[MagickPathExtent], date[MagickPathExtent], **labels, page_geometry[MagickPathExtent]; CompressionType compression; const char *const *s, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType scene; MagickStatusType flags; PixelInfo pixel; PointInfo delta, resolution, scale; Quantum index; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register ssize_t i, x; register unsigned char *q; SegmentInfo bounds; size_t bit, byte, imageListLength, length, page, text_size; ssize_t j, y; time_t timer; unsigned char pixels[2048]; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) memset(&bounds,0,sizeof(bounds)); compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; page=1; scene=0; imageListLength=GetImageListLength(image); do { /* Scale relative to dots-per-inch. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,"%.20gx%.20g", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PS") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MagickPathExtent); (void) ConcatenateMagickString(page_geometry,">",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); if (page == 1) { /* Output Postscript header. */ if (LocaleCompare(image_info->magick,"PS") == 0) (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MagickPathExtent); else (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%Creator: (ImageMagick)\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"%%%%Title: (%s)\n", image->filename); (void) WriteBlobString(image,buffer); timer=time((time_t *) NULL); (void) FormatMagickTime(timer,MagickPathExtent,date); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%CreationDate: (%s)\n",date); (void) WriteBlobString(image,buffer); bounds.x1=(double) geometry.x; bounds.y1=(double) geometry.y; bounds.x2=(double) geometry.x+scale.x; bounds.y2=(double) geometry.y+(geometry.height+text_size); if ((image_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) (void) CopyMagickString(buffer,"%%%%BoundingBox: (atend)\n", MagickPathExtent); else { (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1, bounds.y1,bounds.x2,bounds.y2); } (void) WriteBlobString(image,buffer); profile=GetImageProfile(image,"8bim"); if (profile != (StringInfo *) NULL) { /* Embed Photoshop profile. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%%BeginPhotoshop: %.20g",(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) { if ((i % 32) == 0) (void) WriteBlobString(image,"\n% "); (void) FormatLocaleString(buffer,MagickPathExtent,"%02X", (unsigned int) (GetStringInfoDatum(profile)[i] & 0xff)); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"\n%EndPhotoshop\n"); } profile=GetImageProfile(image,"xmp"); DisableMSCWarning(4127) if (0 && (profile != (StringInfo *) NULL)) RestoreMSCWarning { /* Embed XML profile. */ (void) WriteBlobString(image,"\n%begin_xml_code\n"); (void) FormatLocaleString(buffer,MagickPathExtent, "\n%%begin_xml_packet: %.20g\n",(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) (void) WriteBlobByte(image,GetStringInfoDatum(profile)[i]); (void) WriteBlobString(image,"\n%end_xml_packet\n%end_xml_code\n"); } value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) WriteBlobString(image, "%%DocumentNeededResources: font Times-Roman\n"); (void) WriteBlobString(image,"%%DocumentData: Clean7Bit\n"); (void) WriteBlobString(image,"%%LanguageLevel: 1\n"); if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"%%Pages: 1\n"); else { /* Compute the number of pages. */ (void) WriteBlobString(image,"%%Orientation: Portrait\n"); (void) WriteBlobString(image,"%%PageOrder: Ascend\n"); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%Pages: %.20g\n",image_info->adjoin != MagickFalse ? (double) imageListLength : 1.0); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EndComments\n"); (void) WriteBlobString(image,"\n%%BeginDefaults\n"); (void) WriteBlobString(image,"%%EndDefaults\n\n"); if ((LocaleCompare(image_info->magick,"EPI") == 0) || (LocaleCompare(image_info->magick,"EPSI") == 0) || (LocaleCompare(image_info->magick,"EPT") == 0)) { Image *preview_image; Quantum pixel; register ssize_t x; ssize_t y; /* Create preview image. */ preview_image=CloneImage(image,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Dump image as bitmap. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%BeginPreview: %.20g %.20g %.20g %.20g\n%% ",(double) preview_image->columns,(double) preview_image->rows,1.0, (double) ((((preview_image->columns+7) >> 3)*preview_image->rows+ 35)/36)); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(preview_image,0,y,preview_image->columns,1, exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) preview_image->columns; x++) { byte<<=1; pixel=ClampToQuantum(GetPixelLuma(preview_image,p)); if (pixel >= (Quantum) (QuantumRange/2)) byte|=0x01; bit++; if (bit == 8) { q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; (void) WriteBlobString(image,"% "); }; bit=0; byte=0; } } if (bit != 0) { byte<<=(8-bit); q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; (void) WriteBlobString(image,"% "); }; }; } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } (void) WriteBlobString(image,"\n%%EndPreview\n"); preview_image=DestroyImage(preview_image); } /* Output Postscript commands. */ for (s=PostscriptProlog; *s != (char *) NULL; s++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%s\n",*s); (void) WriteBlobString(image,buffer); } value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) { (void) WriteBlobString(image, " /Times-Roman findfont pointsize scalefont setfont\n"); for (j=(ssize_t) MultilineCensus(value)-1; j >= 0; j--) { (void) WriteBlobString(image," /label 512 string def\n"); (void) WriteBlobString(image, " currentfile label readline pop\n"); (void) FormatLocaleString(buffer,MagickPathExtent, " 0 y %g add moveto label show pop\n",j*pointsize+12); (void) WriteBlobString(image,buffer); } } for (s=PostscriptEpilog; *s != (char *) NULL; s++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%s\n",*s); (void) WriteBlobString(image,buffer); } if (LocaleCompare(image_info->magick,"PS") == 0) (void) WriteBlobString(image," showpage\n"); (void) WriteBlobString(image,"} bind def\n"); (void) WriteBlobString(image,"%%EndProlog\n"); } (void) FormatLocaleString(buffer,MagickPathExtent,"%%%%Page: 1 %.20g\n", (double) (page++)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%PageBoundingBox: %.20g %.20g %.20g %.20g\n",(double) geometry.x, (double) geometry.y,geometry.x+(double) geometry.width,geometry.y+(double) (geometry.height+text_size)); (void) WriteBlobString(image,buffer); if ((double) geometry.x < bounds.x1) bounds.x1=(double) geometry.x; if ((double) geometry.y < bounds.y1) bounds.y1=(double) geometry.y; if ((double) (geometry.x+geometry.width-1) > bounds.x2) bounds.x2=(double) geometry.x+geometry.width-1; if ((double) (geometry.y+(geometry.height+text_size)-1) > bounds.y2) bounds.y2=(double) geometry.y+(geometry.height+text_size)-1; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) WriteBlobString(image,"%%%%PageResources: font Times-Roman\n"); if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"userdict begin\n"); (void) WriteBlobString(image,"DisplayImage\n"); /* Output image data. */ (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n%g %g\n%g\n", (double) geometry.x,(double) geometry.y,scale.x,scale.y,pointsize); (void) WriteBlobString(image,buffer); labels=(char **) NULL; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { for (i=0; labels[i] != (char *) NULL; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%s \n", labels[i]); (void) WriteBlobString(image,buffer); labels[i]=DestroyString(labels[i]); } labels=(char **) RelinquishMagickMemory(labels); } (void) memset(&pixel,0,sizeof(pixel)); pixel.alpha=(MagickRealType) TransparentAlpha; index=0; x=0; if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { if (SetImageMonochrome(image,exception) == MagickFalse) { Quantum pixel; /* Dump image as grayscale. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n1\n1\n1\n8\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(Quantum) ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( image,p))); q=PopHexPixel(hex_digits,(size_t) pixel,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } } else { ssize_t y; Quantum pixel; /* Dump image as bitmap. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n1\n1\n1\n1\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; pixel=ClampToQuantum(GetPixelLuma(image,p)); if (pixel >= (Quantum) (QuantumRange/2)) byte|=0x01; bit++; if (bit == 8) { q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+2) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; }; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+2) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } }; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (image->alpha_trait != UndefinedPixelTrait)) { /* Dump DirectClass image. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n0\n%d\n",(double) image->columns,(double) image->rows, compression == RLECompression ? 1 : 0); (void) WriteBlobString(image,buffer); switch (compression) { case RLECompression: { /* Dump runlength-encoded DirectColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; GetPixelInfoPixel(image,p,&pixel); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((GetPixelRed(image,p) == ClampToQuantum(pixel.red)) && (GetPixelGreen(image,p) == ClampToQuantum(pixel.green)) && (GetPixelBlue(image,p) == ClampToQuantum(pixel.blue)) && (GetPixelAlpha(image,p) == ClampToQuantum(pixel.alpha)) && (length < 255) && (x < (ssize_t) (image->columns-1))) length++; else { if (x > 0) { WriteRunlengthPacket(image,pixel,length,p); if ((q-pixels+10) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } } length=0; } GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); } WriteRunlengthPacket(image,pixel,length,p); if ((q-pixels+10) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case NoCompression: default: { /* Dump uncompressed DirectColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if ((image->alpha_trait != UndefinedPixelTrait) && (GetPixelAlpha(image,p) == (Quantum) TransparentAlpha)) { q=PopHexPixel(hex_digits,0xff,q); q=PopHexPixel(hex_digits,0xff,q); q=PopHexPixel(hex_digits,0xff,q); } else { q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelRed(image,p)),q); q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelGreen(image,p)),q); q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelBlue(image,p)),q); } if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } } (void) WriteBlobByte(image,'\n'); } else { /* Dump PseudoClass image. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n%d\n%d\n0\n",(double) image->columns,(double) image->rows,image->storage_class == PseudoClass ? 1 : 0, compression == RLECompression ? 1 : 0); (void) WriteBlobString(image,buffer); /* Dump number of colors and colormap. */ (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) image->colors); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) image->colors; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%02X%02X%02X\n", ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)), ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)), ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue))); (void) WriteBlobString(image,buffer); } switch (compression) { case RLECompression: { /* Dump runlength-encoded PseudoColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; index=GetPixelIndex(image,p); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((index == GetPixelIndex(image,p)) && (length < 255) && (x < ((ssize_t) image->columns-1))) length++; else { if (x > 0) { q=PopHexPixel(hex_digits,(size_t) index,q); q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); i++; if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } } length=0; } index=GetPixelIndex(image,p); pixel.red=(MagickRealType) GetPixelRed(image,p); pixel.green=(MagickRealType) GetPixelGreen(image,p); pixel.blue=(MagickRealType) GetPixelBlue(image,p); pixel.alpha=(MagickRealType) GetPixelAlpha(image,p); p+=GetPixelChannels(image); } q=PopHexPixel(hex_digits,(size_t) index,q); q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case NoCompression: default: { /* Dump uncompressed PseudoColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { q=PopHexPixel(hex_digits,(size_t) GetPixelIndex(image,p),q); if ((q-pixels+4) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } } (void) WriteBlobByte(image,'\n'); } if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"end\n"); (void) WriteBlobString(image,"%%PageTrailer\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) WriteBlobString(image,"%%Trailer\n"); if (page > 2) { (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2-0.5),floor(bounds.y2-0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1,bounds.x2, bounds.y2); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EOF\n"); (void) CloseBlob(image); return(MagickTrue); }
CWE-787
7
1
formList_addInput(struct form_list *fl, struct parsed_tag *tag) { struct form_item_list *item; char *p; int i; /* if not in <form>..</form> environment, just ignore <input> tag */ if (fl == NULL) return NULL; item = New(struct form_item_list); item->type = FORM_UNKNOWN; item->size = -1; item->rows = 0; item->checked = item->init_checked = 0; item->accept = 0; item->name = NULL; item->value = item->init_value = NULL; item->readonly = 0; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { item->type = formtype(p); if (item->size < 0 && (item->type == FORM_INPUT_TEXT || item->type == FORM_INPUT_FILE || item->type == FORM_INPUT_PASSWORD)) item->size = FORM_I_TEXT_DEFAULT_SIZE; } if (parsedtag_get_value(tag, ATTR_NAME, &p)) item->name = Strnew_charp(p); if (parsedtag_get_value(tag, ATTR_VALUE, &p)) item->value = item->init_value = Strnew_charp(p); item->checked = item->init_checked = parsedtag_exists(tag, ATTR_CHECKED); item->accept = parsedtag_exists(tag, ATTR_ACCEPT); parsedtag_get_value(tag, ATTR_SIZE, &item->size); parsedtag_get_value(tag, ATTR_MAXLENGTH, &item->maxlength); item->readonly = parsedtag_exists(tag, ATTR_READONLY); if (parsedtag_get_value(tag, ATTR_TEXTAREANUMBER, &i)) item->value = item->init_value = textarea_str[i]; #ifdef MENU_SELECT if (parsedtag_get_value(tag, ATTR_SELECTNUMBER, &i)) item->select_option = select_option[i].first; #endif /* MENU_SELECT */ if (parsedtag_get_value(tag, ATTR_ROWS, &p)) item->rows = atoi(p); if (item->type == FORM_UNKNOWN) { /* type attribute is missing. Ignore the tag. */ return NULL; } #ifdef MENU_SELECT if (item->type == FORM_SELECT) { chooseSelectOption(item, item->select_option); item->init_selected = item->selected; item->init_value = item->value; item->init_label = item->label; } #endif /* MENU_SELECT */ if (item->type == FORM_INPUT_FILE && item->value && item->value->length) { /* security hole ! */ return NULL; } item->parent = fl; item->next = NULL; if (fl->item == NULL) { fl->item = fl->lastitem = item; } else { fl->lastitem->next = item; fl->lastitem = item; } if (item->type == FORM_INPUT_HIDDEN) return NULL; fl->nitems++; return item; }
CWE-119
0
1
static int readOHDRHeaderMessageDataLayout(struct READER *reader, struct DATAOBJECT *data) { int i, err; unsigned size; uint8_t dimensionality, layout_class; uint32_t dataset_element_size; uint64_t data_address, store, data_size; UNUSED(dataset_element_size); UNUSED(data_size); if (fgetc(reader->fhd) != 3) { // LCOV_EXCL_START mylog("object OHDR message data layout message must have version 3\n"); return MYSOFA_INVALID_FORMAT; // LCOV_EXCL_STOP } layout_class = (uint8_t)fgetc(reader->fhd); mylog("data layout %d\n", layout_class); switch (layout_class) { #if 0 case 0: data_size = readValue(reader, 2); fseek(reader->fhd, data_size, SEEK_CUR); mylog("TODO 0 SIZE %u\n", data_size); break; #endif case 1: data_address = readValue(reader, reader->superblock.size_of_offsets); data_size = readValue(reader, reader->superblock.size_of_lengths); mylog("CHUNK Contiguous SIZE %" PRIu64 "\n", data_size); if (validAddress(reader, data_address)) { store = ftell(reader->fhd); if (fseek(reader->fhd, data_address, SEEK_SET) < 0) return errno; // LCOV_EXCL_LINE if (!data->data) { if (data_size > 0x10000000) return MYSOFA_INVALID_FORMAT; data->data_len = data_size; data->data = calloc(1, data_size); if (!data->data) return MYSOFA_NO_MEMORY; // LCOV_EXCL_LINE } err = fread(data->data, 1, data_size, reader->fhd); if (err != data_size) return MYSOFA_READ_ERROR; // LCOV_EXCL_LINE if (fseek(reader->fhd, store, SEEK_SET) < 0) return errno; // LCOV_EXCL_LINE } break; case 2: dimensionality = (uint8_t)fgetc(reader->fhd); mylog("dimensionality %d\n", dimensionality); if (dimensionality < 1 || dimensionality > DATAOBJECT_MAX_DIMENSIONALITY) { mylog("data layout 2: invalid dimensionality %d %lu %lu\n", dimensionality, sizeof(data->datalayout_chunk), sizeof(data->datalayout_chunk[0])); return MYSOFA_INVALID_FORMAT; // LCOV_EXCL_LINE } data_address = readValue(reader, reader->superblock.size_of_offsets); mylog(" CHUNK %" PRIX64 "\n", data_address); for (i = 0; i < dimensionality; i++) { data->datalayout_chunk[i] = readValue(reader, 4); mylog(" %d\n", data->datalayout_chunk[i]); } /* TODO last entry? error in spec: ?*/ size = data->datalayout_chunk[dimensionality - 1]; for (i = 0; i < data->ds.dimensionality; i++) size *= data->ds.dimension_size[i]; if (validAddress(reader, data_address) && dimensionality <= 4) { store = ftell(reader->fhd); if (fseek(reader->fhd, data_address, SEEK_SET) < 0) return errno; // LCOV_EXCL_LINE if (!data->data) { if (size > 0x10000000) return MYSOFA_INVALID_FORMAT; // LCOV_EXCL_LINE data->data_len = size; data->data = calloc(1, size); if (!data->data) return MYSOFA_NO_MEMORY; // LCOV_EXCL_LINE } err = treeRead(reader, data); if (err) return err; // LCOV_EXCL_LINE if (fseek(reader->fhd, store, SEEK_SET) < 0) return errno; // LCOV_EXCL_LINE } break; default: // LCOV_EXCL_START mylog("object OHDR message data layout message has unknown layout class " "%d\n", layout_class); return MYSOFA_INVALID_FORMAT; // LCOV_EXCL_STOP } return MYSOFA_OK; }
CWE-787
7
1
i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data, struct drm_file *file) { struct drm_i915_gem_execbuffer2 *args = data; struct drm_i915_gem_exec_object2 *exec2_list; struct drm_syncobj **fences = NULL; const size_t count = args->buffer_count; int err; if (!check_buffer_count(count)) { DRM_DEBUG("execbuf2 with %zd buffers\n", count); return -EINVAL; } if (!i915_gem_check_execbuffer(args)) return -EINVAL; /* Allocate an extra slot for use by the command parser */ exec2_list = kvmalloc_array(count + 1, eb_element_size(), __GFP_NOWARN | GFP_KERNEL); if (exec2_list == NULL) { DRM_DEBUG("Failed to allocate exec list for %zd buffers\n", count); return -ENOMEM; } if (copy_from_user(exec2_list, u64_to_user_ptr(args->buffers_ptr), sizeof(*exec2_list) * count)) { DRM_DEBUG("copy %zd exec entries failed\n", count); kvfree(exec2_list); return -EFAULT; } if (args->flags & I915_EXEC_FENCE_ARRAY) { fences = get_fence_array(args, file); if (IS_ERR(fences)) { kvfree(exec2_list); return PTR_ERR(fences); } } err = i915_gem_do_execbuffer(dev, file, args, exec2_list, fences); /* * Now that we have begun execution of the batchbuffer, we ignore * any new error after this point. Also given that we have already * updated the associated relocations, we try to write out the current * object locations irrespective of any error. */ if (args->flags & __EXEC_HAS_RELOC) { struct drm_i915_gem_exec_object2 __user *user_exec_list = u64_to_user_ptr(args->buffers_ptr); unsigned int i; /* Copy the new buffer offsets back to the user's exec list. */ user_access_begin(); for (i = 0; i < args->buffer_count; i++) { if (!(exec2_list[i].offset & UPDATE)) continue; exec2_list[i].offset = gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK); unsafe_put_user(exec2_list[i].offset, &user_exec_list[i].offset, end_user); } end_user: user_access_end(); } args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS; put_fence_array(args, fences); kvfree(exec2_list); return err; }
CWE-20
2
1
void SafeBrowsingBlockingPage::CommandReceived(const std::string& cmd) { std::string command(cmd); // Make a local copy so we can modify it. if (command.length() > 1 && command[0] == '"') { command = command.substr(1, command.length() - 2); } RecordUserReactionTime(command); if (command == kDoReportCommand) { SetReportingPreference(true); return; } if (command == kDontReportCommand) { SetReportingPreference(false); return; } if (command == kLearnMoreCommand) { GURL url; SBThreatType threat_type = unsafe_resources_[0].threat_type; if (threat_type == SB_THREAT_TYPE_URL_MALWARE) { url = google_util::AppendGoogleLocaleParam(GURL(kLearnMoreMalwareUrl)); } else if (threat_type == SB_THREAT_TYPE_URL_PHISHING || threat_type == SB_THREAT_TYPE_CLIENT_SIDE_PHISHING_URL) { url = google_util::AppendGoogleLocaleParam(GURL(kLearnMorePhishingUrl)); } else { NOTREACHED(); } OpenURLParams params( url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, false); web_contents_->OpenURL(params); return; } if (command == kLearnMoreCommandV2) { GURL url; SBThreatType threat_type = unsafe_resources_[0].threat_type; if (threat_type == SB_THREAT_TYPE_URL_MALWARE) { url = google_util::AppendGoogleLocaleParam(GURL(kLearnMoreMalwareUrlV2)); } else if (threat_type == SB_THREAT_TYPE_URL_PHISHING || threat_type == SB_THREAT_TYPE_CLIENT_SIDE_PHISHING_URL) { url = google_util::AppendGoogleLocaleParam(GURL(kLearnMorePhishingUrlV2)); } else { NOTREACHED(); } OpenURLParams params( url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, false); web_contents_->OpenURL(params); return; } if (command == kShowPrivacyCommand) { GURL url(l10n_util::GetStringUTF8(IDS_SAFE_BROWSING_PRIVACY_POLICY_URL)); OpenURLParams params( url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, false); web_contents_->OpenURL(params); return; } bool proceed_blocked = false; if (command == kProceedCommand) { if (IsPrefEnabled(prefs::kSafeBrowsingProceedAnywayDisabled)) { proceed_blocked = true; } else { interstitial_page_->Proceed(); return; } } if (command == kTakeMeBackCommand || proceed_blocked) { if (is_main_frame_load_blocked_) { interstitial_page_->DontProceed(); return; } if (web_contents_->GetController().CanGoBack()) { web_contents_->GetController().GoBack(); } else { web_contents_->GetController().LoadURL( GURL(chrome::kChromeUINewTabURL), content::Referrer(), content::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } return; } int element_index = 0; size_t colon_index = command.find(':'); if (colon_index != std::string::npos) { DCHECK(colon_index < command.size() - 1); bool result = base::StringToInt(base::StringPiece(command.begin() + colon_index + 1, command.end()), &element_index); command = command.substr(0, colon_index); DCHECK(result); } if (element_index >= static_cast<int>(unsafe_resources_.size())) { NOTREACHED(); return; } std::string bad_url_spec = unsafe_resources_[element_index].url.spec(); if (command == kReportErrorCommand) { SBThreatType threat_type = unsafe_resources_[element_index].threat_type; DCHECK(threat_type == SB_THREAT_TYPE_URL_PHISHING || threat_type == SB_THREAT_TYPE_CLIENT_SIDE_PHISHING_URL); GURL report_url = safe_browsing_util::GeneratePhishingReportUrl( kSbReportPhishingErrorUrl, bad_url_spec, threat_type == SB_THREAT_TYPE_CLIENT_SIDE_PHISHING_URL); OpenURLParams params( report_url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, false); web_contents_->OpenURL(params); return; } if (command == kShowDiagnosticCommand) { std::string diagnostic = base::StringPrintf(kSbDiagnosticUrl, net::EscapeQueryParamValue(bad_url_spec, true).c_str()); GURL diagnostic_url(diagnostic); diagnostic_url = google_util::AppendGoogleLocaleParam(diagnostic_url); DCHECK(unsafe_resources_[element_index].threat_type == SB_THREAT_TYPE_URL_MALWARE); OpenURLParams params( diagnostic_url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, false); web_contents_->OpenURL(params); return; } if (command == kExpandedSeeMore) { return; } NOTREACHED() << "Unexpected command: " << command; }
CWE-119
0