project
stringclasses 633
values | commit_id
stringlengths 7
81
| target
int64 0
1
| func
stringlengths 5
484k
| cwe
stringclasses 131
values | big_vul_idx
float64 0
189k
⌀ | idx
int64 0
522k
| hash
stringlengths 34
39
| size
float64 1
24k
⌀ | message
stringlengths 0
11.5k
⌀ | dataset
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
php
|
809610f5ea38a83b284e1125d1fff129bdd615e7
| 1 |
static int php_handler(request_rec *r)
{
php_struct * volatile ctx;
void *conf;
apr_bucket_brigade * volatile brigade;
apr_bucket *bucket;
apr_status_t rv;
request_rec * volatile parent_req = NULL;
TSRMLS_FETCH();
#define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req TSRMLS_CC);
conf = ap_get_module_config(r->per_dir_config, &php5_module);
/* apply_config() needs r in some cases, so allocate server_context early */
ctx = SG(server_context);
if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) {
normal:
ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx));
/* register a cleanup so we clear out the SG(server_context)
* after each request. Note: We pass in the pointer to the
* server_context in case this is handled by a different thread.
*/
apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null);
ctx->r = r;
ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */
} else {
parent_req = ctx->r;
ctx->r = r;
}
apply_config(conf);
if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) {
/* Check for xbithack in this case. */
if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) {
PHPAP_INI_OFF;
return DECLINED;
}
}
/* Give a 404 if PATH_INFO is used but is explicitly disabled in
* the configuration; default behaviour is to accept. */
if (r->used_path_info == AP_REQ_REJECT_PATH_INFO
&& r->path_info && r->path_info[0]) {
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
/* handle situations where user turns the engine off */
if (!AP2(engine)) {
PHPAP_INI_OFF;
return DECLINED;
}
if (r->finfo.filetype == 0) {
php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
if (r->finfo.filetype == APR_DIR) {
php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_FORBIDDEN;
}
/* Setup the CGI variables if this is the main request */
if (r->main == NULL ||
/* .. or if the sub-request environment differs from the main-request. */
r->subprocess_env != r->main->subprocess_env
) {
/* setup standard CGI variables */
ap_add_common_vars(r);
ap_add_cgi_vars(r);
}
zend_first_try {
if (ctx == NULL) {
brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
ctx = SG(server_context);
ctx->brigade = brigade;
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
} else {
if (!parent_req) {
parent_req = ctx->r;
}
if (parent_req && parent_req->handler &&
strcmp(parent_req->handler, PHP_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SCRIPT)) {
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
}
/*
* check if coming due to ErrorDocument
* We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs
* during processing of the request by PHP during POST processing. Therefor we need to re-use the exiting
* PHP instance to handle the request rather then creating a new one.
*/
if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) {
parent_req = NULL;
goto normal;
}
ctx->r = r;
brigade = ctx->brigade;
}
if (AP2(last_modified)) {
ap_update_mtime(r, r->finfo.mtime);
ap_set_last_modified(r);
}
/* Determine if we need to parse the file or show the source */
if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) {
zend_syntax_highlighter_ini syntax_highlighter_ini;
php_get_highlight_struct(&syntax_highlighter_ini);
highlight_file((char *)r->filename, &syntax_highlighter_ini TSRMLS_CC);
} else {
zend_file_handle zfd;
zfd.type = ZEND_HANDLE_FILENAME;
zfd.filename = (char *) r->filename;
zfd.free_filename = 0;
zfd.opened_path = NULL;
if (!parent_req) {
php_execute_script(&zfd TSRMLS_CC);
} else {
zend_execute_scripts(ZEND_INCLUDE TSRMLS_CC, NULL, 1, &zfd);
}
apr_table_set(r->notes, "mod_php_memory_usage",
apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1 TSRMLS_CC)));
}
} zend_end_try();
if (!parent_req) {
php_apache_request_dtor(r TSRMLS_CC);
ctx->request_processed = 1;
bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
rv = ap_pass_brigade(r->output_filters, brigade);
if (rv != APR_SUCCESS || r->connection->aborted) {
zend_first_try {
php_handle_aborted_connection();
} zend_end_try();
}
apr_brigade_cleanup(brigade);
} else {
ctx->r = parent_req;
}
return OK;
}
|
CWE-20
| 177,882 | 10,272 |
62915396398942948037728837168053920653
| null | null | null |
qemu
|
de594e47659029316bbf9391efb79da0a1a08e08
| 1 |
static void lsi_execute_script(LSIState *s)
{
PCIDevice *pci_dev = PCI_DEVICE(s);
uint32_t insn;
uint32_t addr, addr_high;
int opcode;
int insn_processed = 0;
s->istat1 |= LSI_ISTAT1_SRUN;
again:
s->istat1 |= LSI_ISTAT1_SRUN;
again:
insn_processed++;
insn = read_dword(s, s->dsp);
if (!insn) {
/* If we receive an empty opcode increment the DSP by 4 bytes
s->dbc = insn & 0xffffff;
s->rbc = s->dbc;
/* ??? Set ESA. */
s->ia = s->dsp - 8;
if (insn & (1 << 29)) {
/* Indirect addressing. */
addr = read_dword(s, addr);
} else if (insn & (1 << 28)) {
uint32_t buf[2];
int32_t offset;
/* Table indirect addressing. */
/* 32-bit Table indirect */
offset = sextract32(addr, 0, 24);
pci_dma_read(pci_dev, s->dsa + offset, buf, 8);
/* byte count is stored in bits 0:23 only */
s->dbc = cpu_to_le32(buf[0]) & 0xffffff;
s->rbc = s->dbc;
addr = cpu_to_le32(buf[1]);
/* 40-bit DMA, upper addr bits [39:32] stored in first DWORD of
* table, bits [31:24] */
if (lsi_dma_40bit(s))
addr_high = cpu_to_le32(buf[0]) >> 24;
else if (lsi_dma_ti64bit(s)) {
int selector = (cpu_to_le32(buf[0]) >> 24) & 0x1f;
switch (selector) {
case 0 ... 0x0f:
/* offset index into scratch registers since
* TI64 mode can use registers C to R */
addr_high = s->scratch[2 + selector];
break;
case 0x10:
addr_high = s->mmrs;
break;
case 0x11:
addr_high = s->mmws;
break;
case 0x12:
addr_high = s->sfs;
break;
case 0x13:
addr_high = s->drs;
break;
case 0x14:
addr_high = s->sbms;
break;
case 0x15:
addr_high = s->dbms;
break;
default:
qemu_log_mask(LOG_GUEST_ERROR,
"lsi_scsi: Illegal selector specified (0x%x > 0x15) "
"for 64-bit DMA block move", selector);
break;
}
}
} else if (lsi_dma_64bit(s)) {
/* fetch a 3rd dword if 64-bit direct move is enabled and
only if we're not doing table indirect or indirect addressing */
s->dbms = read_dword(s, s->dsp);
s->dsp += 4;
s->ia = s->dsp - 12;
}
if ((s->sstat1 & PHASE_MASK) != ((insn >> 24) & 7)) {
trace_lsi_execute_script_blockmove_badphase(
scsi_phase_name(s->sstat1),
scsi_phase_name(insn >> 24));
lsi_script_scsi_interrupt(s, LSI_SIST0_MA, 0);
break;
}
s->dnad = addr;
s->dnad64 = addr_high;
switch (s->sstat1 & 0x7) {
case PHASE_DO:
s->waiting = LSI_DMA_SCRIPTS;
lsi_do_dma(s, 1);
if (s->waiting)
s->waiting = LSI_DMA_IN_PROGRESS;
break;
case PHASE_DI:
s->waiting = LSI_DMA_SCRIPTS;
lsi_do_dma(s, 0);
if (s->waiting)
s->waiting = LSI_DMA_IN_PROGRESS;
break;
case PHASE_CMD:
lsi_do_command(s);
break;
case PHASE_ST:
lsi_do_status(s);
break;
case PHASE_MO:
lsi_do_msgout(s);
break;
case PHASE_MI:
lsi_do_msgin(s);
break;
default:
qemu_log_mask(LOG_UNIMP, "lsi_scsi: Unimplemented phase %s\n",
scsi_phase_name(s->sstat1));
}
s->dfifo = s->dbc & 0xff;
s->ctest5 = (s->ctest5 & 0xfc) | ((s->dbc >> 8) & 3);
s->sbc = s->dbc;
s->rbc -= s->dbc;
s->ua = addr + s->dbc;
break;
case 1: /* IO or Read/Write instruction. */
opcode = (insn >> 27) & 7;
if (opcode < 5) {
uint32_t id;
if (insn & (1 << 25)) {
id = read_dword(s, s->dsa + sextract32(insn, 0, 24));
} else {
id = insn;
}
id = (id >> 16) & 0xf;
if (insn & (1 << 26)) {
addr = s->dsp + sextract32(addr, 0, 24);
}
s->dnad = addr;
switch (opcode) {
case 0: /* Select */
s->sdid = id;
if (s->scntl1 & LSI_SCNTL1_CON) {
trace_lsi_execute_script_io_alreadyreselected();
s->dsp = s->dnad;
break;
}
s->sstat0 |= LSI_SSTAT0_WOA;
s->scntl1 &= ~LSI_SCNTL1_IARB;
if (!scsi_device_find(&s->bus, 0, id, 0)) {
lsi_bad_selection(s, id);
break;
}
trace_lsi_execute_script_io_selected(id,
insn & (1 << 3) ? " ATN" : "");
/* ??? Linux drivers compain when this is set. Maybe
it only applies in low-level mode (unimplemented).
lsi_script_scsi_interrupt(s, LSI_SIST0_CMP, 0); */
s->select_tag = id << 8;
s->scntl1 |= LSI_SCNTL1_CON;
if (insn & (1 << 3)) {
s->socl |= LSI_SOCL_ATN;
s->sbcl |= LSI_SBCL_ATN;
}
s->sbcl |= LSI_SBCL_BSY;
lsi_set_phase(s, PHASE_MO);
s->waiting = LSI_NOWAIT;
break;
case 1: /* Disconnect */
trace_lsi_execute_script_io_disconnect();
s->scntl1 &= ~LSI_SCNTL1_CON;
/* FIXME: this is not entirely correct; the target need not ask
* for reselection until it has to send data, while here we force a
* reselection as soon as the bus is free. The correct flow would
* reselect before lsi_transfer_data and disconnect as soon as
* DMA ends.
*/
if (!s->current) {
lsi_request *p = get_pending_req(s);
if (p) {
lsi_reselect(s, p);
}
}
break;
case 2: /* Wait Reselect */
if (s->istat0 & LSI_ISTAT0_SIGP) {
s->dsp = s->dnad;
} else if (!lsi_irq_on_rsl(s)) {
lsi_wait_reselect(s);
}
break;
case 3: /* Set */
trace_lsi_execute_script_io_set(
insn & (1 << 3) ? " ATN" : "",
insn & (1 << 6) ? " ACK" : "",
insn & (1 << 9) ? " TM" : "",
insn & (1 << 10) ? " CC" : "");
if (insn & (1 << 3)) {
s->socl |= LSI_SOCL_ATN;
s->sbcl |= LSI_SBCL_ATN;
lsi_set_phase(s, PHASE_MO);
}
if (insn & (1 << 6)) {
s->sbcl |= LSI_SBCL_ACK;
}
if (insn & (1 << 9)) {
qemu_log_mask(LOG_UNIMP,
"lsi_scsi: Target mode not implemented\n");
}
if (insn & (1 << 10))
s->carry = 1;
break;
case 4: /* Clear */
trace_lsi_execute_script_io_clear(
insn & (1 << 3) ? " ATN" : "",
insn & (1 << 6) ? " ACK" : "",
insn & (1 << 9) ? " TM" : "",
insn & (1 << 10) ? " CC" : "");
if (insn & (1 << 3)) {
s->socl &= ~LSI_SOCL_ATN;
s->sbcl &= ~LSI_SBCL_ATN;
}
if (insn & (1 << 6)) {
s->sbcl &= ~LSI_SBCL_ACK;
}
if (insn & (1 << 10))
s->carry = 0;
break;
}
} else {
uint8_t op0;
uint8_t op1;
uint8_t data8;
int reg;
int operator;
static const char *opcode_names[3] =
{"Write", "Read", "Read-Modify-Write"};
static const char *operator_names[8] =
{"MOV", "SHL", "OR", "XOR", "AND", "SHR", "ADD", "ADC"};
reg = ((insn >> 16) & 0x7f) | (insn & 0x80);
data8 = (insn >> 8) & 0xff;
opcode = (insn >> 27) & 7;
operator = (insn >> 24) & 7;
trace_lsi_execute_script_io_opcode(
opcode_names[opcode - 5], reg,
operator_names[operator], data8, s->sfbr,
(insn & (1 << 23)) ? " SFBR" : "");
op0 = op1 = 0;
switch (opcode) {
case 5: /* From SFBR */
op0 = s->sfbr;
op1 = data8;
break;
case 6: /* To SFBR */
if (operator)
op0 = lsi_reg_readb(s, reg);
op1 = data8;
break;
case 7: /* Read-modify-write */
if (operator)
op0 = lsi_reg_readb(s, reg);
if (insn & (1 << 23)) {
op1 = s->sfbr;
} else {
op1 = data8;
}
break;
}
switch (operator) {
case 0: /* move */
op0 = op1;
break;
case 1: /* Shift left */
op1 = op0 >> 7;
op0 = (op0 << 1) | s->carry;
s->carry = op1;
break;
case 2: /* OR */
op0 |= op1;
break;
case 3: /* XOR */
op0 ^= op1;
break;
case 4: /* AND */
op0 &= op1;
break;
case 5: /* SHR */
op1 = op0 & 1;
op0 = (op0 >> 1) | (s->carry << 7);
s->carry = op1;
break;
case 6: /* ADD */
op0 += op1;
s->carry = op0 < op1;
break;
case 7: /* ADC */
op0 += op1 + s->carry;
if (s->carry)
s->carry = op0 <= op1;
else
s->carry = op0 < op1;
break;
}
switch (opcode) {
case 5: /* From SFBR */
case 7: /* Read-modify-write */
lsi_reg_writeb(s, reg, op0);
break;
case 6: /* To SFBR */
s->sfbr = op0;
break;
}
}
break;
case 2: /* Transfer Control. */
{
int cond;
int jmp;
if ((insn & 0x002e0000) == 0) {
trace_lsi_execute_script_tc_nop();
break;
}
if (s->sist1 & LSI_SIST1_STO) {
trace_lsi_execute_script_tc_delayedselect_timeout();
lsi_stop_script(s);
break;
}
cond = jmp = (insn & (1 << 19)) != 0;
if (cond == jmp && (insn & (1 << 21))) {
trace_lsi_execute_script_tc_compc(s->carry == jmp);
cond = s->carry != 0;
}
if (cond == jmp && (insn & (1 << 17))) {
trace_lsi_execute_script_tc_compp(scsi_phase_name(s->sstat1),
jmp ? '=' : '!', scsi_phase_name(insn >> 24));
cond = (s->sstat1 & PHASE_MASK) == ((insn >> 24) & 7);
}
if (cond == jmp && (insn & (1 << 18))) {
uint8_t mask;
mask = (~insn >> 8) & 0xff;
trace_lsi_execute_script_tc_compd(
s->sfbr, mask, jmp ? '=' : '!', insn & mask);
cond = (s->sfbr & mask) == (insn & mask);
}
if (cond == jmp) {
if (insn & (1 << 23)) {
/* Relative address. */
addr = s->dsp + sextract32(addr, 0, 24);
}
switch ((insn >> 27) & 7) {
case 0: /* Jump */
trace_lsi_execute_script_tc_jump(addr);
s->adder = addr;
s->dsp = addr;
break;
case 1: /* Call */
trace_lsi_execute_script_tc_call(addr);
s->temp = s->dsp;
s->dsp = addr;
break;
case 2: /* Return */
trace_lsi_execute_script_tc_return(s->temp);
s->dsp = s->temp;
break;
case 3: /* Interrupt */
trace_lsi_execute_script_tc_interrupt(s->dsps);
if ((insn & (1 << 20)) != 0) {
s->istat0 |= LSI_ISTAT0_INTF;
lsi_update_irq(s);
} else {
lsi_script_dma_interrupt(s, LSI_DSTAT_SIR);
}
break;
default:
trace_lsi_execute_script_tc_illegal();
lsi_script_dma_interrupt(s, LSI_DSTAT_IID);
break;
}
} else {
trace_lsi_execute_script_tc_cc_failed();
}
}
break;
case 3:
if ((insn & (1 << 29)) == 0) {
/* Memory move. */
uint32_t dest;
/* ??? The docs imply the destination address is loaded into
the TEMP register. However the Linux drivers rely on
the value being presrved. */
dest = read_dword(s, s->dsp);
s->dsp += 4;
lsi_memcpy(s, dest, addr, insn & 0xffffff);
} else {
uint8_t data[7];
int reg;
int n;
int i;
if (insn & (1 << 28)) {
addr = s->dsa + sextract32(addr, 0, 24);
}
n = (insn & 7);
reg = (insn >> 16) & 0xff;
if (insn & (1 << 24)) {
pci_dma_read(pci_dev, addr, data, n);
trace_lsi_execute_script_mm_load(reg, n, addr, *(int *)data);
for (i = 0; i < n; i++) {
lsi_reg_writeb(s, reg + i, data[i]);
}
} else {
trace_lsi_execute_script_mm_store(reg, n, addr);
for (i = 0; i < n; i++) {
data[i] = lsi_reg_readb(s, reg + i);
}
pci_dma_write(pci_dev, addr, data, n);
}
}
}
if (insn_processed > 10000 && s->waiting == LSI_NOWAIT) {
/* Some windows drivers make the device spin waiting for a memory
location to change. If we have been executed a lot of code then
assume this is the case and force an unexpected device disconnect.
This is apparently sufficient to beat the drivers into submission.
*/
if (!(s->sien0 & LSI_SIST0_UDC)) {
qemu_log_mask(LOG_GUEST_ERROR,
"lsi_scsi: inf. loop with UDC masked");
}
lsi_script_scsi_interrupt(s, LSI_SIST0_UDC, 0);
lsi_disconnect(s);
} else if (s->istat1 & LSI_ISTAT1_SRUN && s->waiting == LSI_NOWAIT) {
if (s->dcntl & LSI_DCNTL_SSM) {
}
}
}
|
CWE-835
| 177,894 | 10,273 |
244108805153871264712854024106060934668
| null | null | null |
qemu
|
c689b4f1bac352dcfd6ecb9a1d45337de0f1de67
| 1 |
static void become_daemon(const char *pidfile)
{
#ifndef _WIN32
pid_t pid, sid;
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
if (pidfile) {
if (!ga_open_pidfile(pidfile)) {
g_critical("failed to create pidfile");
exit(EXIT_FAILURE);
}
}
umask(0);
sid = setsid();
if (sid < 0) {
goto fail;
}
if ((chdir("/")) < 0) {
goto fail;
}
reopen_fd_to_null(STDIN_FILENO);
reopen_fd_to_null(STDOUT_FILENO);
reopen_fd_to_null(STDERR_FILENO);
return;
fail:
if (pidfile) {
unlink(pidfile);
}
g_critical("failed to daemonize");
exit(EXIT_FAILURE);
#endif
}
|
CWE-264
| 177,896 | 10,274 |
38956668855577330785462954593650386270
| null | null | null |
php
|
188c196d4da60bdde9190d2fc532650d17f7af2d
| 1 |
xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
ctxt->keepBlanks = 0;
ctxt->options -= XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
}
|
CWE-200
| 177,897 | 10,275 |
172553444095414967939735908896702455968
| null | null | null |
php
|
188c196d4da60bdde9190d2fc532650d17f7af2d
| 1 |
xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
/*
xmlInitParser();
*/
ctxt = xmlCreateMemoryParserCtxt(buf, buf_size);
if (ctxt) {
ctxt->options -= XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
#if LIBXML_VERSION >= 20703
ctxt->options |= XML_PARSE_HUGE;
#endif
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
/*
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
*/
return ret;
}
|
CWE-200
| 177,898 | 10,276 |
127103460148010706040652829136393768763
| null | null | null |
php
|
afe98b7829d50806559acac9b530acb8283c3bf4
| 1 |
xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
ctxt->keepBlanks = 0;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
/*ctxt->sax->fatalError = NULL;*/
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
}
|
CWE-200
| 177,899 | 10,277 |
233412514791180458146881803056011855351
| null | null | null |
php
|
afe98b7829d50806559acac9b530acb8283c3bf4
| 1 |
xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
/*
xmlInitParser();
*/
*/
ctxt = xmlCreateMemoryParserCtxt(buf, buf_size);
if (ctxt) {
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
#if LIBXML_VERSION >= 20703
ctxt->options |= XML_PARSE_HUGE;
#endif
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
/*
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
*/
return ret;
}
|
CWE-200
| 177,900 | 10,278 |
317087771483047414535963980097477807718
| null | null | null |
php
|
8e76d0404b7f664ee6719fd98f0483f0ac4669d6
| 1 |
static PHP_GINIT_FUNCTION(libxml)
{
libxml_globals->stream_context = NULL;
libxml_globals->error_buffer.c = NULL;
libxml_globals->error_list = NULL;
}
|
CWE-200
| 177,916 | 10,279 |
168761678947878649312416820048693204338
| null | null | null |
libx11
|
dbf72805fd9d7b1846fe9a11b46f3994bfc27fea
| 1 |
char **XListExtensions(
register Display *dpy,
int *nextensions) /* RETURN */
{
xListExtensionsReply rep;
char **list = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetEmptyReq (ListExtensions, req);
if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nExtensions) {
list = Xmalloc (rep.nExtensions * sizeof (char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc (rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((!list) || (!ch)) {
Xfree(list);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + rlen;
length = *ch;
for (i = 0; i < rep.nExtensions; i++) {
if (ch + length < chend) {
list[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else
list[i] = NULL;
}
}
*nextensions = count;
UnlockDisplay(dpy);
SyncHandle();
return (list);
}
|
CWE-787
| 177,918 | 10,281 |
257782681708195618663023486677304847820
| null | null | null |
php
|
1291d6bbee93b6109eb07e8f7916ff1b7fcc13e1
| 1 |
PHP_FUNCTION(move_uploaded_file)
{
char *path, *new_path;
int path_len, new_path_len;
zend_bool successful = 0;
#ifndef PHP_WIN32
int oldmask; int ret;
#endif
if (!SG(rfc1867_uploaded_files)) {
RETURN_FALSE;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &new_path, &new_path_len) == FAILURE) {
return;
}
if (!zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) {
RETURN_FALSE;
}
if (php_check_open_basedir(new_path TSRMLS_CC)) {
RETURN_FALSE;
}
if (VCWD_RENAME(path, new_path) == 0) {
successful = 1;
#ifndef PHP_WIN32
oldmask = umask(077);
umask(oldmask);
ret = VCWD_CHMOD(new_path, 0666 & ~oldmask);
if (ret == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno));
}
#endif
} else if (php_copy_file_ex(path, new_path, STREAM_DISABLE_OPEN_BASEDIR TSRMLS_CC) == SUCCESS) {
VCWD_UNLINK(path);
successful = 1;
}
if (successful) {
zend_hash_del(SG(rfc1867_uploaded_files), path, path_len + 1);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to move '%s' to '%s'", path, new_path);
}
RETURN_BOOL(successful);
}
|
CWE-264
| 177,923 | 10,282 |
217589831576282368127909842388570409340
| null | null | null |
php
|
ef8fc4b53d92fbfcd8ef1abbd6f2f5fe2c4a11e5
| 1 |
_zip_cdir_new(int nentry, struct zip_error *error)
{
struct zip_cdir *cd;
if ((cd=(struct zip_cdir *)malloc(sizeof(*cd))) == NULL) {
_zip_error_set(error, ZIP_ER_MEMORY, 0);
return NULL;
}
if ((cd->entry=(struct zip_dirent *)malloc(sizeof(*(cd->entry))*nentry))
== NULL) {
_zip_error_set(error, ZIP_ER_MEMORY, 0);
free(cd);
return NULL;
}
/* entries must be initialized by caller */
cd->nentry = nentry;
cd->size = cd->offset = 0;
cd->comment = NULL;
cd->comment_len = 0;
return cd;
}
|
CWE-189
| 177,924 | 10,283 |
54000566122250771000946321340482488552
| null | null | null |
php
|
b2cf3f064b8f5efef89bb084521b61318c71781b
| 1 |
static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */
{
const char *oldname = NULL;
char *oldpath = NULL;
char *basename = NULL, *basepath = NULL;
char *newname = NULL, *newpath = NULL;
zval *ret, arg1;
zend_class_entry *ce;
char *error;
const char *pcr_error;
int ext_len = ext ? strlen(ext) : 0;
int oldname_len;
phar_archive_data **pphar = NULL;
php_stream_statbuf ssb;
if (!ext) {
if (phar->is_zip) {
if (phar->is_data) {
ext = "zip";
} else {
ext = "phar.zip";
}
} else if (phar->is_tar) {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
if (phar->is_data) {
ext = "tar.gz";
} else {
ext = "phar.tar.gz";
}
break;
case PHAR_FILE_COMPRESSED_BZ2:
if (phar->is_data) {
ext = "tar.bz2";
} else {
ext = "phar.tar.bz2";
}
break;
default:
if (phar->is_data) {
ext = "tar";
} else {
ext = "phar.tar";
}
}
} else {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
ext = "phar.gz";
break;
case PHAR_FILE_COMPRESSED_BZ2:
ext = "phar.bz2";
break;
default:
ext = "phar";
}
}
} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
if (phar->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
}
return NULL;
}
if (ext[0] == '.') {
++ext;
}
oldpath = estrndup(phar->fname, phar->fname_len);
oldname = zend_memrchr(phar->fname, '/', phar->fname_len);
++oldname;
oldname_len = strlen(oldname);
basename = estrndup(oldname, oldname_len);
spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext);
efree(basename);
basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
phar->fname = newpath;
phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
efree(basepath);
efree(newname);
if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname);
return NULL;
}
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {
if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {
if (!zend_hash_num_elements(&phar->manifest)) {
(*pphar)->is_tar = phar->is_tar;
(*pphar)->is_zip = phar->is_zip;
(*pphar)->is_data = phar->is_data;
(*pphar)->flags = phar->flags;
(*pphar)->fp = phar->fp;
phar->fp = NULL;
phar_destroy_phar_data(phar TSRMLS_CC);
phar = *pphar;
phar->refcount++;
newpath = oldpath;
goto its_ok;
}
}
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname);
return NULL;
}
its_ok:
if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
return NULL;
}
if (!phar->is_data) {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
if (phar->alias) {
if (phar->is_temporary_alias) {
phar->alias = NULL;
phar->alias_len = 0;
} else {
phar->alias = estrndup(newpath, strlen(newpath));
phar->alias_len = strlen(newpath);
phar->is_temporary_alias = 1;
zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);
}
}
} else {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
phar->alias = NULL;
phar->alias_len = 0;
}
if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
return NULL;
}
phar_flush(phar, 0, 0, 1, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
efree(error);
efree(oldpath);
return NULL;
}
efree(oldpath);
if (phar->is_data) {
ce = phar_ce_data;
} else {
ce = phar_ce_archive;
}
MAKE_STD_ZVAL(ret);
if (SUCCESS != object_init_ex(ret, ce)) {
zval_dtor(ret);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
return NULL;
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);
zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1);
return ret;
}
/* }}} */
| 177,925 | 10,284 |
162248037189449008653572496503407425010
| null | null | null |
|
php
|
73cabfedf519298e1a11192699f44d53c529315e
| 1 |
PHP_FUNCTION(openssl_seal)
{
zval *pubkeys, *pubkey, *sealdata, *ekeys, *iv = NULL;
HashTable *pubkeysht;
EVP_PKEY **pkeys;
zend_resource ** key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys, iv_len;
unsigned char iv_buf[EVP_MAX_IV_LENGTH + 1], *buf = NULL, **eks;
char * data;
size_t data_len;
char *method =NULL;
size_t method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX *ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz/z/a/|sz/", &data, &data_len,
&sealdata, &ekeys, &pubkeys, &method, &method_len, &iv) == FAILURE) {
return;
}
pubkeysht = Z_ARRVAL_P(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
iv_len = EVP_CIPHER_iv_length(cipher);
if (!iv && iv_len > 0) {
php_error_docref(NULL, E_WARNING,
"Cipher algorithm requires an IV to be supplied as a sixth parameter");
RETURN_FALSE;
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(zend_resource*), 0);
memset(key_resources, 0, sizeof(zend_resource*) * nkeys);
memset(pkeys, 0, sizeof(*pkeys) * nkeys);
/* get the public keys we are using to seal this data */
i = 0;
ZEND_HASH_FOREACH_VAL(pubkeysht, pubkey) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, 0, &key_resources[i]);
if (pkeys[i] == NULL) {
php_error_docref(NULL, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
i++;
} ZEND_HASH_FOREACH_END();
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL || !EVP_EncryptInit(ctx,cipher,NULL,NULL)) {
EVP_CIPHER_CTX_free(ctx);
RETVAL_FALSE;
goto clean_exit;
}
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx));
EVP_CIPHER_CTX_cleanup(ctx);
if (!EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) ||
!EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) ||
!EVP_SealFinal(ctx, buf + len1, &len2)) {
RETVAL_FALSE;
efree(buf);
EVP_CIPHER_CTX_free(ctx);
goto clean_exit;
}
if (len1 + len2 > 0) {
zval_dtor(sealdata);
ZVAL_NEW_STR(sealdata, zend_string_init((char*)buf, len1 + len2, 0));
efree(buf);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, (const char*)eks[i], eksl[i]);
efree(eks[i]);
eks[i] = NULL;
}
if (iv) {
zval_dtor(iv);
iv_buf[iv_len] = '\0';
ZVAL_NEW_STR(iv, zend_string_init((char*)iv_buf, iv_len, 0));
}
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_free(ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == NULL && pkeys[i] != NULL) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
}
|
CWE-754
| 177,927 | 10,285 |
274013670007838824436232406087394037753
| null | null | null |
php
|
91826a311dd37f4c4e5d605fa7af331e80ddd4c3
| 1 |
PHP_FUNCTION(openssl_seal)
{
zval *pubkeys, *pubkey, *sealdata, *ekeys, *iv = NULL;
HashTable *pubkeysht;
EVP_PKEY **pkeys;
zend_resource ** key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys, iv_len;
unsigned char iv_buf[EVP_MAX_IV_LENGTH + 1], *buf = NULL, **eks;
char * data;
size_t data_len;
char *method =NULL;
size_t method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX *ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz/z/a/|sz/", &data, &data_len,
&sealdata, &ekeys, &pubkeys, &method, &method_len, &iv) == FAILURE) {
return;
}
pubkeysht = Z_ARRVAL_P(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data);
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
iv_len = EVP_CIPHER_iv_length(cipher);
if (!iv && iv_len > 0) {
php_error_docref(NULL, E_WARNING,
"Cipher algorithm requires an IV to be supplied as a sixth parameter");
RETURN_FALSE;
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(zend_resource*), 0);
memset(key_resources, 0, sizeof(zend_resource*) * nkeys);
memset(pkeys, 0, sizeof(*pkeys) * nkeys);
/* get the public keys we are using to seal this data */
i = 0;
ZEND_HASH_FOREACH_VAL(pubkeysht, pubkey) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, 0, &key_resources[i]);
if (pkeys[i] == NULL) {
php_error_docref(NULL, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
i++;
} ZEND_HASH_FOREACH_END();
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL || !EVP_EncryptInit(ctx,cipher,NULL,NULL)) {
EVP_CIPHER_CTX_free(ctx);
php_openssl_store_errors();
RETVAL_FALSE;
goto clean_exit;
}
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx));
EVP_CIPHER_CTX_cleanup(ctx);
if (!EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) ||
!EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) ||
!EVP_SealFinal(ctx, buf + len1, &len2)) {
efree(buf);
EVP_CIPHER_CTX_free(ctx);
php_openssl_store_errors();
RETVAL_FALSE;
goto clean_exit;
}
if (len1 + len2 > 0) {
zval_dtor(sealdata);
ZVAL_NEW_STR(sealdata, zend_string_init((char*)buf, len1 + len2, 0));
efree(buf);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, (const char*)eks[i], eksl[i]);
efree(eks[i]);
eks[i] = NULL;
}
if (iv) {
zval_dtor(iv);
iv_buf[iv_len] = '\0';
ZVAL_NEW_STR(iv, zend_string_init((char*)iv_buf, iv_len, 0));
}
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_free(ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == NULL && pkeys[i] != NULL) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
}
|
CWE-754
| 177,928 | 10,286 |
278149621899021665677086590146431573987
| null | null | null |
php
|
89637c6b41b510c20d262c17483f582f115c66d6
| 1 |
PHP_FUNCTION(openssl_seal)
{
zval *pubkeys, **pubkey, *sealdata, *ekeys;
HashTable *pubkeysht;
HashPosition pos;
EVP_PKEY **pkeys;
long * key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys;
unsigned char *buf = NULL, **eks;
char * data; int data_len;
char *method =NULL;
int method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szza/|s", &data, &data_len, &sealdata, &ekeys, &pubkeys, &method, &method_len) == FAILURE) {
return;
}
pubkeysht = HASH_OF(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
if (EVP_CIPHER_iv_length(cipher) > 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Ciphers with modes requiring IV are not supported");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(long), 0);
memset(key_resources, 0, sizeof(*key_resources) * nkeys);
/* get the public keys we are using to seal this data */
zend_hash_internal_pointer_reset_ex(pubkeysht, &pos);
i = 0;
while (zend_hash_get_current_data_ex(pubkeysht, (void **) &pubkey,
&pos) == SUCCESS) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, &key_resources[i] TSRMLS_CC);
if (pkeys[i] == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
zend_hash_move_forward_ex(pubkeysht, &pos);
i++;
}
if (!EVP_EncryptInit(&ctx,cipher,NULL,NULL)) {
RETVAL_FALSE;
EVP_CIPHER_CTX_cleanup(&ctx);
goto clean_exit;
}
#if 0
/* Need this if allow ciphers that require initialization vector */
ivlen = EVP_CIPHER_CTX_iv_length(&ctx);
iv = ivlen ? emalloc(ivlen + 1) : NULL;
#endif
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(&ctx));
EVP_CIPHER_CTX_cleanup(&ctx);
if (!EVP_SealInit(&ctx, cipher, eks, eksl, NULL, pkeys, nkeys) || !EVP_SealUpdate(&ctx, buf, &len1, (unsigned char *)data, data_len)) {
RETVAL_FALSE;
efree(buf);
EVP_CIPHER_CTX_cleanup(&ctx);
goto clean_exit;
}
EVP_SealFinal(&ctx, buf + len1, &len2);
if (len1 + len2 > 0) {
zval_dtor(sealdata);
buf[len1 + len2] = '\0';
buf = erealloc(buf, len1 + len2 + 1);
ZVAL_STRINGL(sealdata, (char *)buf, len1 + len2, 0);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, erealloc(eks[i], eksl[i] + 1), eksl[i], 0);
eks[i] = NULL;
}
#if 0
/* If allow ciphers that need IV, we need this */
zval_dtor(*ivec);
if (ivlen) {
iv[ivlen] = '\0';
ZVAL_STRINGL(*ivec, erealloc(iv, ivlen + 1), ivlen, 0);
} else {
ZVAL_EMPTY_STRING(*ivec);
}
#endif
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_cleanup(&ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == -1) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
}
|
CWE-754
| 177,929 | 10,287 |
44760629731898782091119208085385158717
| null | null | null |
php
|
2aae60461c2ff7b7fbcdd194c789ac841d0747d7
| 1 |
static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1]));
break;
}
} else {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ZVAL_FALSE(&ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
} else if (!strcmp(name, EL_NULL)) {
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i+1]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
i++;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
|
CWE-502
| 177,930 | 10,288 |
191425631551549845965177325135024965574
| null | null | null |
gstreamer
|
bdc20b9baf13564d9a061343416395f8f9a92b53
| 1 |
qtdemux_parse_samples (GstQTDemux * qtdemux, QtDemuxStream * stream,
GNode * stbl)
{
int offset;
GNode *stsc;
GNode *stsz;
GNode *stco;
GNode *co64;
GNode *stts;
GNode *stss;
GNode *ctts;
const guint8 *stsc_data, *stsz_data, *stco_data;
int sample_size;
int sample_index;
int n_samples;
int n_samples_per_chunk;
int n_sample_times;
QtDemuxSample *samples;
gint i, j, k;
int index;
guint64 timestamp, time;
/* sample to chunk */
if (!(stsc = qtdemux_tree_get_child_by_type (stbl, FOURCC_stsc)))
goto corrupt_file;
stsc_data = (const guint8 *) stsc->data;
/* sample size */
if (!(stsz = qtdemux_tree_get_child_by_type (stbl, FOURCC_stsz)))
goto corrupt_file;
stsz_data = (const guint8 *) stsz->data;
/* chunk offsets */
stco = qtdemux_tree_get_child_by_type (stbl, FOURCC_stco);
co64 = qtdemux_tree_get_child_by_type (stbl, FOURCC_co64);
if (stco) {
stco_data = (const guint8 *) stco->data;
} else {
stco_data = NULL;
if (co64 == NULL)
goto corrupt_file;
}
/* sample time */
if (!(stts = qtdemux_tree_get_child_by_type (stbl, FOURCC_stts)))
goto corrupt_file;
/* sample sync, can be NULL */
stss = qtdemux_tree_get_child_by_type (stbl, FOURCC_stss);
sample_size = QT_UINT32 (stsz_data + 12);
if (sample_size == 0 || stream->sampled) {
n_samples = QT_UINT32 (stsz_data + 16);
GST_DEBUG_OBJECT (qtdemux, "stsz sample_size 0, allocating n_samples %d",
n_samples);
stream->n_samples = n_samples;
samples = g_new0 (QtDemuxSample, n_samples);
stream->samples = samples;
for (i = 0; i < n_samples; i++) {
if (sample_size == 0)
samples[i].size = QT_UINT32 (stsz_data + i * 4 + 20);
else
samples[i].size = sample_size;
GST_LOG_OBJECT (qtdemux, "sample %d has size %d", i, samples[i].size);
/* init other fields to defaults for this sample */
samples[i].keyframe = FALSE;
}
n_samples_per_chunk = QT_UINT32 (stsc_data + 12);
index = 0;
for (i = 0; i < n_samples_per_chunk; i++) {
guint32 first_chunk, last_chunk;
guint32 samples_per_chunk;
first_chunk = QT_UINT32 (stsc_data + 16 + i * 12 + 0) - 1;
if (i == n_samples_per_chunk - 1) {
last_chunk = G_MAXUINT32;
} else {
last_chunk = QT_UINT32 (stsc_data + 16 + i * 12 + 12) - 1;
}
samples_per_chunk = QT_UINT32 (stsc_data + 16 + i * 12 + 4);
for (j = first_chunk; j < last_chunk; j++) {
guint64 chunk_offset;
if (stco) {
chunk_offset = QT_UINT32 (stco_data + 16 + j * 4);
} else {
chunk_offset = QT_UINT64 ((guint8 *) co64->data + 16 + j * 8);
}
for (k = 0; k < samples_per_chunk; k++) {
GST_LOG_OBJECT (qtdemux, "Creating entry %d with offset %lld",
index, chunk_offset);
samples[index].chunk = j;
samples[index].offset = chunk_offset;
chunk_offset += samples[index].size;
index++;
if (index >= n_samples)
goto done2;
}
}
}
done2:
n_sample_times = QT_UINT32 ((guint8 *) stts->data + 12);
timestamp = 0;
stream->min_duration = 0;
time = 0;
index = 0;
for (i = 0; i < n_sample_times; i++) {
guint32 n;
guint32 duration;
n = QT_UINT32 ((guint8 *) stts->data + 16 + 8 * i);
duration = QT_UINT32 ((guint8 *) stts->data + 16 + 8 * i + 4);
for (j = 0; j < n; j++) {
GST_DEBUG_OBJECT (qtdemux, "sample %d: timestamp %" GST_TIME_FORMAT,
index, GST_TIME_ARGS (timestamp));
samples[index].timestamp = timestamp;
/* take first duration for fps */
if (stream->min_duration == 0)
stream->min_duration = duration;
/* add non-scaled values to avoid rounding errors */
time += duration;
timestamp = gst_util_uint64_scale (time, GST_SECOND, stream->timescale);
samples[index].duration = timestamp - samples[index].timestamp;
index++;
}
}
if (stss) {
/* mark keyframes */
guint32 n_sample_syncs;
n_sample_syncs = QT_UINT32 ((guint8 *) stss->data + 12);
if (n_sample_syncs == 0) {
stream->all_keyframe = TRUE;
} else {
offset = 16;
for (i = 0; i < n_sample_syncs; i++) {
/* note that the first sample is index 1, not 0 */
index = QT_UINT32 ((guint8 *) stss->data + offset);
if (index > 0) {
samples[index - 1].keyframe = TRUE;
offset += 4;
}
}
}
} else {
/* no stss, all samples are keyframes */
stream->all_keyframe = TRUE;
}
} else {
GST_DEBUG_OBJECT (qtdemux,
"stsz sample_size %d != 0, treating chunks as samples", sample_size);
/* treat chunks as samples */
if (stco) {
n_samples = QT_UINT32 (stco_data + 12);
} else {
n_samples = QT_UINT32 ((guint8 *) co64->data + 12);
}
stream->n_samples = n_samples;
GST_DEBUG_OBJECT (qtdemux, "allocating n_samples %d", n_samples);
samples = g_new0 (QtDemuxSample, n_samples);
stream->samples = samples;
n_samples_per_chunk = QT_UINT32 (stsc_data + 12);
GST_DEBUG_OBJECT (qtdemux, "n_samples_per_chunk %d", n_samples_per_chunk);
sample_index = 0;
timestamp = 0;
for (i = 0; i < n_samples_per_chunk; i++) {
guint32 first_chunk, last_chunk;
guint32 samples_per_chunk;
first_chunk = QT_UINT32 (stsc_data + 16 + i * 12 + 0) - 1;
/* the last chunk of each entry is calculated by taking the first chunk
* of the next entry; except if there is no next, where we fake it with
* INT_MAX */
if (i == n_samples_per_chunk - 1) {
last_chunk = G_MAXUINT32;
} else {
last_chunk = QT_UINT32 (stsc_data + 16 + i * 12 + 12) - 1;
}
samples_per_chunk = QT_UINT32 (stsc_data + 16 + i * 12 + 4);
GST_LOG_OBJECT (qtdemux,
"entry %d has first_chunk %d, last_chunk %d, samples_per_chunk %d", i,
first_chunk, last_chunk, samples_per_chunk);
for (j = first_chunk; j < last_chunk; j++) {
guint64 chunk_offset;
if (j >= n_samples)
goto done;
if (stco) {
chunk_offset = QT_UINT32 (stco_data + 16 + j * 4);
} else {
chunk_offset = QT_UINT64 ((guint8 *) co64->data + 16 + j * 8);
}
GST_LOG_OBJECT (qtdemux,
"Creating entry %d with offset %" G_GUINT64_FORMAT, j,
chunk_offset);
samples[j].chunk = j;
samples[j].offset = chunk_offset;
if (stream->samples_per_frame * stream->bytes_per_frame) {
samples[j].size = (samples_per_chunk * stream->n_channels) /
stream->samples_per_frame * stream->bytes_per_frame;
} else {
samples[j].size = samples_per_chunk;
}
GST_DEBUG_OBJECT (qtdemux, "sample %d: timestamp %" GST_TIME_FORMAT
", size %u", j, GST_TIME_ARGS (timestamp), samples[j].size);
samples[j].timestamp = timestamp;
sample_index += samples_per_chunk;
timestamp = gst_util_uint64_scale (sample_index,
GST_SECOND, stream->timescale);
samples[j].duration = timestamp - samples[j].timestamp;
samples[j].keyframe = TRUE;
}
}
}
/* composition time to sample */
if ((ctts = qtdemux_tree_get_child_by_type (stbl, FOURCC_ctts))) {
const guint8 *ctts_data = (const guint8 *) ctts->data;
guint32 n_entries = QT_UINT32 (ctts_data + 12);
guint32 count;
gint32 soffset;
/* Fill in the pts_offsets */
for (i = 0, j = 0; (j < stream->n_samples) && (i < n_entries); i++) {
count = QT_UINT32 (ctts_data + 16 + i * 8);
soffset = QT_UINT32 (ctts_data + 20 + i * 8);
for (k = 0; k < count; k++, j++) {
/* we operate with very small soffset values here, it shouldn't overflow */
samples[j].pts_offset = soffset * GST_SECOND / stream->timescale;
}
}
}
done:
return TRUE;
/* ERRORS */
corrupt_file:
{
GST_ELEMENT_ERROR (qtdemux, STREAM, DECODE,
(_("This file is corrupt and cannot be played.")), (NULL));
return FALSE;
}
}
|
CWE-119
| 177,938 | 10,289 |
106880796511915682295530864306063302037
| null | null | null |
php
|
124fb22a13fafa3648e4e15b4f207c7096d8155e
| 1 |
static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table) /* {{{ */
{
char *table_copy, *escaped, *token, *tmp;
size_t len;
/* schame.table should be "schame"."table" */
table_copy = estrdup(table);
token = php_strtok_r(table_copy, ".", &tmp);
len = strlen(token);
if (_php_pgsql_detect_identifier_escape(token, len) == SUCCESS) {
smart_str_appendl(querystr, token, len);
PGSQLfree(escaped);
}
if (tmp && *tmp) {
len = strlen(tmp);
/* "schema"."table" format */
if (_php_pgsql_detect_identifier_escape(tmp, len) == SUCCESS) {
smart_str_appendc(querystr, '.');
smart_str_appendl(querystr, tmp, len);
} else {
escaped = PGSQLescapeIdentifier(pg_link, tmp, len);
smart_str_appendc(querystr, '.');
smart_str_appends(querystr, escaped);
PGSQLfree(escaped);
}
}
efree(table_copy);
}
/* }}} */
| 177,941 | 10,291 |
26612874507061928700178447943250062560
| null | null | null |
|
php
|
777c39f4042327eac4b63c7ee87dc1c7a09a3115
| 1 |
void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source)
{
void *old_p, *retval;
if ((old_p = zend_hash_index_find_ptr(&xlat_table, (zend_ulong)source)) != NULL) {
/* we already duplicated this pointer */
return old_p;
}
retval = ZCG(mem);
ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size));
memcpy(retval, source, size);
if (free_source) {
efree(source);
}
zend_shared_alloc_register_xlat_entry(source, retval);
return retval;
}
|
CWE-416
| 177,942 | 10,292 |
16602847189087668222849493796241390763
| null | null | null |
qemu
|
96d87bdda3919bb16f754b3d3fd1227e1f38f13c
| 1 |
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid)
{
XHCIEPContext *epctx;
assert(slotid >= 1 && slotid <= xhci->numslots);
assert(epid >= 1 && epid <= 31);
if (!xhci->slots[slotid-1].enabled) {
DPRINTF("xhci: xhci_kick_ep for disabled slot %d\n", slotid);
return;
}
epctx = xhci->slots[slotid-1].eps[epid-1];
if (!epctx) {
DPRINTF("xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
epid, slotid);
return;
return;
}
xhci_kick_epctx(epctx, streamid);
}
|
CWE-835
| 177,967 | 10,293 |
108164519926752861822718030746395221306
| null | null | null |
qemu
|
d710e1e7bd3d5bfc26b631f02ae87901ebe646b0
| 1 |
static void usb_ehci_pci_exit(PCIDevice *dev)
{
EHCIPCIState *i = PCI_EHCI(dev);
static void usb_ehci_pci_reset(DeviceState *dev)
{
PCIDevice *pci_dev = PCI_DEVICE(dev);
EHCIPCIState *i = PCI_EHCI(pci_dev);
EHCIState *s = &i->ehci;
ehci_reset(s);
}
static void usb_ehci_pci_write_config(PCIDevice *dev, uint32_t addr,
uint32_t val, int l)
{
EHCIPCIState *i = PCI_EHCI(dev);
bool busmaster;
pci_default_write_config(dev, addr, val, l);
if (!range_covers_byte(addr, l, PCI_COMMAND)) {
return;
}
busmaster = pci_get_word(dev->config + PCI_COMMAND) & PCI_COMMAND_MASTER;
i->ehci.as = busmaster ? pci_get_address_space(dev) : &address_space_memory;
}
static Property ehci_pci_properties[] = {
DEFINE_PROP_UINT32("maxframes", EHCIPCIState, ehci.maxframes, 128),
DEFINE_PROP_END_OF_LIST(),
};
static const VMStateDescription vmstate_ehci_pci = {
.name = "ehci",
.version_id = 2,
.minimum_version_id = 1,
.fields = (VMStateField[]) {
VMSTATE_PCI_DEVICE(pcidev, EHCIPCIState),
VMSTATE_STRUCT(ehci, EHCIPCIState, 2, vmstate_ehci, EHCIState),
VMSTATE_END_OF_LIST()
}
};
static void ehci_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
k->realize = usb_ehci_pci_realize;
k->exit = usb_ehci_pci_exit;
k->class_id = PCI_CLASS_SERIAL_USB;
k->config_write = usb_ehci_pci_write_config;
dc->vmsd = &vmstate_ehci_pci;
dc->props = ehci_pci_properties;
dc->reset = usb_ehci_pci_reset;
}
static const TypeInfo ehci_pci_type_info = {
.name = TYPE_PCI_EHCI,
.parent = TYPE_PCI_DEVICE,
.instance_size = sizeof(EHCIPCIState),
.instance_init = usb_ehci_pci_init,
.abstract = true,
.class_init = ehci_class_init,
};
static void ehci_data_class_init(ObjectClass *klass, void *data)
.parent = TYPE_PCI_DEVICE,
.instance_size = sizeof(EHCIPCIState),
.instance_init = usb_ehci_pci_init,
.abstract = true,
.class_init = ehci_class_init,
};
|
CWE-772
| 177,968 | 10,294 |
121903533516345620541784213921466434297
| null | null | null |
qemu
|
d68f0f778e7f4fbd674627274267f269e40f0b04
| 1 |
void ahci_uninit(AHCIState *s)
{
g_free(s->dev);
}
|
CWE-772
| 177,969 | 10,295 |
106076214205370295268313409818268570893
| null | null | null |
qemu
|
26f670a244982335cc08943fb1ec099a2c81e42d
| 1 |
static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed,
int completion)
{
int dir;
size_t len = 0;
const char *str = NULL;
int pid;
int ret;
int i;
USBDevice *dev;
USBEndpoint *ep;
struct ohci_iso_td iso_td;
uint32_t addr;
uint16_t starting_frame;
int16_t relative_frame_number;
int frame_count;
uint32_t start_offset, next_offset, end_offset = 0;
uint32_t start_addr, end_addr;
addr = ed->head & OHCI_DPTR_MASK;
if (ohci_read_iso_td(ohci, addr, &iso_td)) {
trace_usb_ohci_iso_td_read_failed(addr);
ohci_die(ohci);
return 0;
}
starting_frame = OHCI_BM(iso_td.flags, TD_SF);
frame_count = OHCI_BM(iso_td.flags, TD_FC);
relative_frame_number = USUB(ohci->frame_number, starting_frame);
trace_usb_ohci_iso_td_head(
ed->head & OHCI_DPTR_MASK, ed->tail & OHCI_DPTR_MASK,
iso_td.flags, iso_td.bp, iso_td.next, iso_td.be,
ohci->frame_number, starting_frame,
frame_count, relative_frame_number);
trace_usb_ohci_iso_td_head_offset(
iso_td.offset[0], iso_td.offset[1],
iso_td.offset[2], iso_td.offset[3],
iso_td.offset[4], iso_td.offset[5],
iso_td.offset[6], iso_td.offset[7]);
if (relative_frame_number < 0) {
trace_usb_ohci_iso_td_relative_frame_number_neg(relative_frame_number);
return 1;
} else if (relative_frame_number > frame_count) {
/* ISO TD expired - retire the TD to the Done Queue and continue with
the next ISO TD of the same ED */
trace_usb_ohci_iso_td_relative_frame_number_big(relative_frame_number,
frame_count);
OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
ed->head &= ~OHCI_DPTR_MASK;
ed->head |= (iso_td.next & OHCI_DPTR_MASK);
iso_td.next = ohci->done;
ohci->done = addr;
i = OHCI_BM(iso_td.flags, TD_DI);
if (i < ohci->done_count)
ohci->done_count = i;
if (ohci_put_iso_td(ohci, addr, &iso_td)) {
ohci_die(ohci);
return 1;
}
return 0;
}
dir = OHCI_BM(ed->flags, ED_D);
switch (dir) {
case OHCI_TD_DIR_IN:
str = "in";
pid = USB_TOKEN_IN;
break;
case OHCI_TD_DIR_OUT:
str = "out";
pid = USB_TOKEN_OUT;
break;
case OHCI_TD_DIR_SETUP:
str = "setup";
pid = USB_TOKEN_SETUP;
break;
default:
trace_usb_ohci_iso_td_bad_direction(dir);
return 1;
}
if (!iso_td.bp || !iso_td.be) {
trace_usb_ohci_iso_td_bad_bp_be(iso_td.bp, iso_td.be);
return 1;
}
start_offset = iso_td.offset[relative_frame_number];
next_offset = iso_td.offset[relative_frame_number + 1];
if (!(OHCI_BM(start_offset, TD_PSW_CC) & 0xe) ||
((relative_frame_number < frame_count) &&
!(OHCI_BM(next_offset, TD_PSW_CC) & 0xe))) {
trace_usb_ohci_iso_td_bad_cc_not_accessed(start_offset, next_offset);
return 1;
}
if ((relative_frame_number < frame_count) && (start_offset > next_offset)) {
trace_usb_ohci_iso_td_bad_cc_overrun(start_offset, next_offset);
return 1;
}
if ((start_offset & 0x1000) == 0) {
start_addr = (iso_td.bp & OHCI_PAGE_MASK) |
(start_offset & OHCI_OFFSET_MASK);
} else {
start_addr = (iso_td.be & OHCI_PAGE_MASK) |
(start_offset & OHCI_OFFSET_MASK);
}
if (relative_frame_number < frame_count) {
end_offset = next_offset - 1;
if ((end_offset & 0x1000) == 0) {
end_addr = (iso_td.bp & OHCI_PAGE_MASK) |
(end_offset & OHCI_OFFSET_MASK);
} else {
end_addr = (iso_td.be & OHCI_PAGE_MASK) |
(end_offset & OHCI_OFFSET_MASK);
}
} else {
/* Last packet in the ISO TD */
end_addr = iso_td.be;
}
if ((start_addr & OHCI_PAGE_MASK) != (end_addr & OHCI_PAGE_MASK)) {
len = (end_addr & OHCI_OFFSET_MASK) + 0x1001
- (start_addr & OHCI_OFFSET_MASK);
} else {
len = end_addr - start_addr + 1;
}
if (len && dir != OHCI_TD_DIR_IN) {
if (ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, len,
DMA_DIRECTION_TO_DEVICE)) {
ohci_die(ohci);
return 1;
}
}
if (!completion) {
bool int_req = relative_frame_number == frame_count &&
OHCI_BM(iso_td.flags, TD_DI) == 0;
dev = ohci_find_device(ohci, OHCI_BM(ed->flags, ED_FA));
ep = usb_ep_get(dev, pid, OHCI_BM(ed->flags, ED_EN));
usb_packet_setup(&ohci->usb_packet, pid, ep, 0, addr, false, int_req);
usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, len);
usb_handle_packet(dev, &ohci->usb_packet);
if (ohci->usb_packet.status == USB_RET_ASYNC) {
usb_device_flush_ep_queue(dev, ep);
return 1;
}
}
if (ohci->usb_packet.status == USB_RET_SUCCESS) {
ret = ohci->usb_packet.actual_length;
} else {
ret = ohci->usb_packet.status;
}
trace_usb_ohci_iso_td_so(start_offset, end_offset, start_addr, end_addr,
str, len, ret);
/* Writeback */
if (dir == OHCI_TD_DIR_IN && ret >= 0 && ret <= len) {
/* IN transfer succeeded */
if (ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, ret,
DMA_DIRECTION_FROM_DEVICE)) {
ohci_die(ohci);
return 1;
}
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_NOERROR);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, ret);
} else if (dir == OHCI_TD_DIR_OUT && ret == len) {
/* OUT transfer succeeded */
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_NOERROR);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, 0);
} else {
if (ret > (ssize_t) len) {
trace_usb_ohci_iso_td_data_overrun(ret, len);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_DATAOVERRUN);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
len);
} else if (ret >= 0) {
trace_usb_ohci_iso_td_data_underrun(ret);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_DATAUNDERRUN);
} else {
switch (ret) {
case USB_RET_IOERROR:
case USB_RET_NODEV:
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_DEVICENOTRESPONDING);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
0);
break;
case USB_RET_NAK:
case USB_RET_STALL:
trace_usb_ohci_iso_td_nak(ret);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_STALL);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
0);
break;
default:
trace_usb_ohci_iso_td_bad_response(ret);
OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
OHCI_CC_UNDEXPETEDPID);
break;
}
}
}
if (relative_frame_number == frame_count) {
/* Last data packet of ISO TD - retire the TD to the Done Queue */
OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_NOERROR);
ed->head &= ~OHCI_DPTR_MASK;
ed->head |= (iso_td.next & OHCI_DPTR_MASK);
iso_td.next = ohci->done;
ohci->done = addr;
i = OHCI_BM(iso_td.flags, TD_DI);
if (i < ohci->done_count)
ohci->done_count = i;
}
if (ohci_put_iso_td(ohci, addr, &iso_td)) {
ohci_die(ohci);
}
return 1;
}
|
CWE-835
| 177,970 | 10,296 |
45572261348269181011041233544164791451
| null | null | null |
php
|
270a406ac94b5fc5cc9ef59fc61e3b4b95648a3e
| 1 |
PHP_FUNCTION(openssl_encrypt)
{
zend_bool raw_output = 0;
char *data, *method, *password, *iv = "";
int data_len, method_len, password_len, iv_len = 0, max_iv_len;
const EVP_CIPHER *cipher_type;
EVP_CIPHER_CTX cipher_ctx;
int i, outlen, keylen;
unsigned char *outbuf, *key;
zend_bool free_iv;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_output, &iv, &iv_len) == FAILURE) {
return;
}
cipher_type = EVP_get_cipherbyname(method);
if (!cipher_type) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
RETURN_FALSE;
}
keylen = EVP_CIPHER_key_length(cipher_type);
if (keylen > password_len) {
key = emalloc(keylen);
memset(key, 0, keylen);
memcpy(key, password, password_len);
} else {
key = (unsigned char*)password;
}
max_iv_len = EVP_CIPHER_iv_length(cipher_type);
if (iv_len <= 0 && max_iv_len > 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Using an empty Initialization Vector (iv) is potentially insecure and not recommended");
}
free_iv = php_openssl_validate_iv(&iv, &iv_len, max_iv_len TSRMLS_CC);
outlen = data_len + EVP_CIPHER_block_size(cipher_type);
outbuf = emalloc(outlen + 1);
EVP_EncryptInit(&cipher_ctx, cipher_type, NULL, NULL);
if (password_len > keylen) {
EVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len);
}
EVP_EncryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv);
if (data_len > 0) {
EVP_EncryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);
}
outlen = i;
if (EVP_EncryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {
outlen += i;
if (raw_output) {
outbuf[outlen] = '\0';
RETVAL_STRINGL((char *)outbuf, outlen, 0);
} else {
int base64_str_len;
char *base64_str;
base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len);
efree(outbuf);
RETVAL_STRINGL(base64_str, base64_str_len, 0);
}
} else {
efree(outbuf);
RETVAL_FALSE;
}
if (key != (unsigned char*)password) {
efree(key);
}
if (free_iv) {
efree(iv);
}
EVP_CIPHER_CTX_cleanup(&cipher_ctx);
}
|
CWE-200
| 177,977 | 10,299 |
321058781952984133924443218004390892133
| null | null | null |
qemu
|
3251bdcf1c67427d964517053c3d185b46e618e8
| 1 |
static int bmdma_prepare_buf(IDEDMA *dma, int is_write)
{
BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);
IDEState *s = bmdma_active_if(bm);
uint32_t size;
} prd;
|
CWE-399
| 178,012 | 10,302 |
239205886887027603674338209569496646767
| null | null | null |
php
|
f9ad3086693fce680fbe246e4a45aa92edd2ac35
| 1 |
int main(int argc, char *argv[])
{
int free_query_string = 0;
int exit_status = SUCCESS;
int cgi = 0, c, i, len;
zend_file_handle file_handle;
char *s;
/* temporary locals */
int behavior = PHP_MODE_STANDARD;
int no_headers = 0;
int orig_optind = php_optind;
char *orig_optarg = php_optarg;
char *script_file = NULL;
int ini_entries_len = 0;
/* end of temporary locals */
#ifdef ZTS
void ***tsrm_ls;
#endif
int max_requests = 500;
int requests = 0;
int fastcgi;
char *bindpath = NULL;
int fcgi_fd = 0;
fcgi_request *request = NULL;
int repeats = 1;
int benchmark = 0;
#if HAVE_GETTIMEOFDAY
struct timeval start, end;
#else
time_t start, end;
#endif
#ifndef PHP_WIN32
int status = 0;
#endif
char *query_string;
char *decoded_query_string;
int skip_getopt = 0;
#if 0 && defined(PHP_DEBUG)
/* IIS is always making things more difficult. This allows
* us to stop PHP and attach a debugger before much gets started */
{
char szMessage [256];
wsprintf (szMessage, "Please attach a debugger to the process 0x%X [%d] (%s) and click OK", GetCurrentProcessId(), GetCurrentProcessId(), argv[0]);
MessageBox(NULL, szMessage, "CGI Debug Time!", MB_OK|MB_SERVICE_NOTIFICATION);
}
#endif
#ifdef HAVE_SIGNAL_H
#if defined(SIGPIPE) && defined(SIG_IGN)
signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
that sockets created via fsockopen()
don't kill PHP if the remote site
closes it. in apache|apxs mode apache
does that for us! thies@thieso.net
20000419 */
#endif
#endif
#ifdef ZTS
tsrm_startup(1, 1, 0, NULL);
tsrm_ls = ts_resource(0);
#endif
sapi_startup(&cgi_sapi_module);
fastcgi = fcgi_is_fastcgi();
cgi_sapi_module.php_ini_path_override = NULL;
#ifdef PHP_WIN32
_fmode = _O_BINARY; /* sets default for file streams to binary */
setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */
setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
#endif
if (!fastcgi) {
/* Make sure we detect we are a cgi - a bit redundancy here,
* but the default case is that we have to check only the first one. */
if (getenv("SERVER_SOFTWARE") ||
getenv("SERVER_NAME") ||
getenv("GATEWAY_INTERFACE") ||
getenv("REQUEST_METHOD")
) {
cgi = 1;
}
}
if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
/* we've got query string that has no = - apache CGI will pass it to command line */
unsigned char *p;
decoded_query_string = strdup(query_string);
php_url_decode(decoded_query_string, strlen(decoded_query_string));
for (p = decoded_query_string; *p && *p <= ' '; p++) {
/* skip all leading spaces */
}
if(*p == '-') {
skip_getopt = 1;
}
free(decoded_query_string);
}
while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
switch (c) {
case 'c':
if (cgi_sapi_module.php_ini_path_override) {
free(cgi_sapi_module.php_ini_path_override);
}
cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
break;
case 'n':
cgi_sapi_module.php_ini_ignore = 1;
break;
case 'd': {
/* define ini entries on command line */
int len = strlen(php_optarg);
char *val;
if ((val = strchr(php_optarg, '='))) {
val++;
if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
ini_entries_len += (val - php_optarg);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
ini_entries_len++;
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
ini_entries_len += len - (val - php_optarg);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
ini_entries_len += sizeof("\n\0\"") - 2;
} else {
cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
ini_entries_len += len + sizeof("\n\0") - 2;
}
} else {
cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
ini_entries_len += len + sizeof("=1\n\0") - 2;
}
break;
}
/* if we're started on command line, check to see if
* we are being started as an 'external' fastcgi
* server by accepting a bindpath parameter. */
case 'b':
if (!fastcgi) {
bindpath = strdup(php_optarg);
}
break;
case 's': /* generate highlighted HTML from source */
behavior = PHP_MODE_HIGHLIGHT;
break;
}
}
php_optind = orig_optind;
php_optarg = orig_optarg;
if (fastcgi || bindpath) {
/* Override SAPI callbacks */
cgi_sapi_module.ub_write = sapi_fcgi_ub_write;
cgi_sapi_module.flush = sapi_fcgi_flush;
cgi_sapi_module.read_post = sapi_fcgi_read_post;
cgi_sapi_module.getenv = sapi_fcgi_getenv;
cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies;
}
#ifdef ZTS
SG(request_info).path_translated = NULL;
#endif
cgi_sapi_module.executable_location = argv[0];
if (!cgi && !fastcgi && !bindpath) {
cgi_sapi_module.additional_functions = additional_functions;
}
/* startup after we get the above ini override se we get things right */
if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
#ifdef ZTS
tsrm_shutdown();
#endif
return FAILURE;
}
/* check force_cgi after startup, so we have proper output */
if (cgi && CGIG(force_redirect)) {
/* Apache will generate REDIRECT_STATUS,
* Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
* redirect.so and installation instructions available from
* http://www.koehntopp.de/php.
* -- kk@netuse.de
*/
if (!getenv("REDIRECT_STATUS") &&
!getenv ("HTTP_REDIRECT_STATUS") &&
/* this is to allow a different env var to be configured
* in case some server does something different than above */
(!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
) {
zend_try {
SG(sapi_headers).http_response_code = 400;
PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
<p>This PHP CGI binary was compiled with force-cgi-redirect enabled. This\n\
means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
set, e.g. via an Apache Action directive.</p>\n\
<p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
manual page for CGI security</a>.</p>\n\
<p>For more information about changing this behaviour or re-enabling this webserver,\n\
consult the installation file that came with this distribution, or visit \n\
<a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
} zend_catch {
} zend_end_try();
#if defined(ZTS) && !defined(PHP_DEBUG)
/* XXX we're crashing here in msvc6 debug builds at
* php_message_handler_for_zend:839 because
* SG(request_info).path_translated is an invalid pointer.
* It still happens even though I set it to null, so something
* weird is going on.
*/
tsrm_shutdown();
#endif
return FAILURE;
}
}
if (bindpath) {
fcgi_fd = fcgi_listen(bindpath, 128);
if (fcgi_fd < 0) {
fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
#ifdef ZTS
tsrm_shutdown();
#endif
return FAILURE;
}
fastcgi = fcgi_is_fastcgi();
}
if (fastcgi) {
/* How many times to run PHP scripts before dying */
if (getenv("PHP_FCGI_MAX_REQUESTS")) {
max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
if (max_requests < 0) {
fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
return FAILURE;
}
}
/* make php call us to get _ENV vars */
php_php_import_environment_variables = php_import_environment_variables;
php_import_environment_variables = cgi_php_import_environment_variables;
/* library is already initialized, now init our request */
request = fcgi_init_request(fcgi_fd);
#ifndef PHP_WIN32
/* Pre-fork, if required */
if (getenv("PHP_FCGI_CHILDREN")) {
char * children_str = getenv("PHP_FCGI_CHILDREN");
children = atoi(children_str);
if (children < 0) {
fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
return FAILURE;
}
fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
/* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, children_str, strlen(children_str));
} else {
fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, "1", sizeof("1")-1);
}
if (children) {
int running = 0;
pid_t pid;
/* Create a process group for ourself & children */
setsid();
pgroup = getpgrp();
#ifdef DEBUG_FASTCGI
fprintf(stderr, "Process group %d\n", pgroup);
#endif
/* Set up handler to kill children upon exit */
act.sa_flags = 0;
act.sa_handler = fastcgi_cleanup;
if (sigaction(SIGTERM, &act, &old_term) ||
sigaction(SIGINT, &act, &old_int) ||
sigaction(SIGQUIT, &act, &old_quit)
) {
perror("Can't set signals");
exit(1);
}
if (fcgi_in_shutdown()) {
goto parent_out;
}
while (parent) {
do {
#ifdef DEBUG_FASTCGI
fprintf(stderr, "Forking, %d running\n", running);
#endif
pid = fork();
switch (pid) {
case 0:
/* One of the children.
* Make sure we don't go round the
* fork loop any more
*/
parent = 0;
/* don't catch our signals */
sigaction(SIGTERM, &old_term, 0);
sigaction(SIGQUIT, &old_quit, 0);
sigaction(SIGINT, &old_int, 0);
break;
case -1:
perror("php (pre-forking)");
exit(1);
break;
default:
/* Fine */
running++;
break;
}
} while (parent && (running < children));
if (parent) {
#ifdef DEBUG_FASTCGI
fprintf(stderr, "Wait for kids, pid %d\n", getpid());
#endif
parent_waiting = 1;
while (1) {
if (wait(&status) >= 0) {
running--;
break;
} else if (exit_signal) {
break;
}
}
if (exit_signal) {
#if 0
while (running > 0) {
while (wait(&status) < 0) {
}
running--;
}
#endif
goto parent_out;
}
}
}
} else {
parent = 0;
}
#endif /* WIN32 */
}
zend_first_try {
while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
switch (c) {
case 'T':
benchmark = 1;
repeats = atoi(php_optarg);
#ifdef HAVE_GETTIMEOFDAY
gettimeofday(&start, NULL);
#else
time(&start);
#endif
break;
case 'h':
case '?':
if (request) {
fcgi_destroy_request(request);
}
fcgi_shutdown();
no_headers = 1;
SG(headers_sent) = 1;
php_cgi_usage(argv[0]);
php_output_end_all(TSRMLS_C);
exit_status = 0;
goto out;
}
}
php_optind = orig_optind;
php_optarg = orig_optarg;
/* start of FAST CGI loop */
/* Initialise FastCGI request structure */
#ifdef PHP_WIN32
/* attempt to set security impersonation for fastcgi
* will only happen on NT based OS, others will ignore it. */
if (fastcgi && CGIG(impersonate)) {
fcgi_impersonate();
}
#endif
while (!fastcgi || fcgi_accept_request(request) >= 0) {
SG(server_context) = fastcgi ? (void *) request : (void *) 1;
init_request_info(request TSRMLS_CC);
CG(interactive) = 0;
if (!cgi && !fastcgi) {
while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
switch (c) {
case 'a': /* interactive mode */
printf("Interactive mode enabled\n\n");
CG(interactive) = 1;
break;
case 'C': /* don't chdir to the script directory */
SG(options) |= SAPI_OPTION_NO_CHDIR;
break;
case 'e': /* enable extended info output */
CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
break;
case 'f': /* parse file */
if (script_file) {
efree(script_file);
}
script_file = estrdup(php_optarg);
no_headers = 1;
break;
case 'i': /* php info & quit */
if (script_file) {
efree(script_file);
}
if (php_request_startup(TSRMLS_C) == FAILURE) {
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
return FAILURE;
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
php_print_info(0xFFFFFFFF TSRMLS_CC);
php_request_shutdown((void *) 0);
fcgi_shutdown();
exit_status = 0;
goto out;
case 'l': /* syntax check mode */
no_headers = 1;
behavior = PHP_MODE_LINT;
break;
case 'm': /* list compiled in modules */
if (script_file) {
efree(script_file);
}
SG(headers_sent) = 1;
php_printf("[PHP Modules]\n");
print_modules(TSRMLS_C);
php_printf("\n[Zend Modules]\n");
print_extensions(TSRMLS_C);
php_printf("\n");
php_output_end_all(TSRMLS_C);
fcgi_shutdown();
exit_status = 0;
goto out;
#if 0 /* not yet operational, see also below ... */
case '': /* generate indented source mode*/
behavior=PHP_MODE_INDENT;
break;
#endif
case 'q': /* do not generate HTTP headers */
no_headers = 1;
break;
case 'v': /* show php version & quit */
if (script_file) {
efree(script_file);
}
no_headers = 1;
if (php_request_startup(TSRMLS_C) == FAILURE) {
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
return FAILURE;
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
#if ZEND_DEBUG
php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
#else
php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
#endif
php_request_shutdown((void *) 0);
fcgi_shutdown();
exit_status = 0;
goto out;
case 'w':
behavior = PHP_MODE_STRIP;
break;
case 'z': /* load extension file */
zend_load_extension(php_optarg);
break;
default:
break;
}
}
if (script_file) {
/* override path_translated if -f on command line */
STR_FREE(SG(request_info).path_translated);
SG(request_info).path_translated = script_file;
/* before registering argv to module exchange the *new* argv[0] */
/* we can achieve this without allocating more memory */
SG(request_info).argc = argc - (php_optind - 1);
SG(request_info).argv = &argv[php_optind - 1];
SG(request_info).argv[0] = script_file;
} else if (argc > php_optind) {
/* file is on command line, but not in -f opt */
STR_FREE(SG(request_info).path_translated);
SG(request_info).path_translated = estrdup(argv[php_optind]);
/* arguments after the file are considered script args */
SG(request_info).argc = argc - php_optind;
SG(request_info).argv = &argv[php_optind];
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
/* all remaining arguments are part of the query string
* this section of code concatenates all remaining arguments
* into a single string, seperating args with a &
* this allows command lines like:
*
* test.php v1=test v2=hello+world!
* test.php "v1=test&v2=hello world!"
* test.php v1=test "v2=hello world!"
*/
if (!SG(request_info).query_string && argc > php_optind) {
int slen = strlen(PG(arg_separator).input);
len = 0;
for (i = php_optind; i < argc; i++) {
if (i < (argc - 1)) {
len += strlen(argv[i]) + slen;
} else {
len += strlen(argv[i]);
}
}
len += 2;
s = malloc(len);
*s = '\0'; /* we are pretending it came from the environment */
for (i = php_optind; i < argc; i++) {
strlcat(s, argv[i], len);
if (i < (argc - 1)) {
strlcat(s, PG(arg_separator).input, len);
}
}
SG(request_info).query_string = s;
free_query_string = 1;
}
} /* end !cgi && !fastcgi */
/*
we never take stdin if we're (f)cgi, always
rely on the web server giving us the info
we need in the environment.
*/
if (SG(request_info).path_translated || cgi || fastcgi) {
file_handle.type = ZEND_HANDLE_FILENAME;
file_handle.filename = SG(request_info).path_translated;
file_handle.handle.fp = NULL;
} else {
file_handle.filename = "-";
file_handle.type = ZEND_HANDLE_FP;
file_handle.handle.fp = stdin;
}
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
/* request startup only after we've done all we can to
* get path_translated */
if (php_request_startup(TSRMLS_C) == FAILURE) {
if (fastcgi) {
fcgi_finish_request(request, 1);
}
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
return FAILURE;
}
if (no_headers) {
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
}
/*
at this point path_translated will be set if:
1. we are running from shell and got filename was there
2. we are running as cgi or fastcgi
*/
if (cgi || fastcgi || SG(request_info).path_translated) {
if (php_fopen_primary_script(&file_handle TSRMLS_CC) == FAILURE) {
zend_try {
if (errno == EACCES) {
SG(sapi_headers).http_response_code = 403;
PUTS("Access denied.\n");
} else {
SG(sapi_headers).http_response_code = 404;
PUTS("No input file specified.\n");
}
} zend_catch {
} zend_end_try();
/* we want to serve more requests if this is fastcgi
* so cleanup and continue, request shutdown is
* handled later */
if (fastcgi) {
goto fastcgi_request_done;
}
STR_FREE(SG(request_info).path_translated);
if (free_query_string && SG(request_info).query_string) {
free(SG(request_info).query_string);
SG(request_info).query_string = NULL;
}
php_request_shutdown((void *) 0);
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
sapi_shutdown();
#ifdef ZTS
tsrm_shutdown();
#endif
return FAILURE;
}
}
if (CGIG(check_shebang_line)) {
/* #!php support */
switch (file_handle.type) {
case ZEND_HANDLE_FD:
if (file_handle.handle.fd < 0) {
break;
}
file_handle.type = ZEND_HANDLE_FP;
file_handle.handle.fp = fdopen(file_handle.handle.fd, "rb");
/* break missing intentionally */
case ZEND_HANDLE_FP:
if (!file_handle.handle.fp ||
(file_handle.handle.fp == stdin)) {
break;
}
c = fgetc(file_handle.handle.fp);
if (c == '#') {
while (c != '\n' && c != '\r' && c != EOF) {
c = fgetc(file_handle.handle.fp); /* skip to end of line */
}
/* handle situations where line is terminated by \r\n */
if (c == '\r') {
if (fgetc(file_handle.handle.fp) != '\n') {
long pos = ftell(file_handle.handle.fp);
fseek(file_handle.handle.fp, pos - 1, SEEK_SET);
}
}
CG(start_lineno) = 2;
} else {
rewind(file_handle.handle.fp);
}
break;
case ZEND_HANDLE_STREAM:
c = php_stream_getc((php_stream*)file_handle.handle.stream.handle);
if (c == '#') {
while (c != '\n' && c != '\r' && c != EOF) {
c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); /* skip to end of line */
}
/* handle situations where line is terminated by \r\n */
if (c == '\r') {
if (php_stream_getc((php_stream*)file_handle.handle.stream.handle) != '\n') {
long pos = php_stream_tell((php_stream*)file_handle.handle.stream.handle);
php_stream_seek((php_stream*)file_handle.handle.stream.handle, pos - 1, SEEK_SET);
}
}
CG(start_lineno) = 2;
} else {
php_stream_rewind((php_stream*)file_handle.handle.stream.handle);
}
break;
case ZEND_HANDLE_MAPPED:
if (file_handle.handle.stream.mmap.buf[0] == '#') {
int i = 1;
c = file_handle.handle.stream.mmap.buf[i++];
while (c != '\n' && c != '\r' && c != EOF) {
c = file_handle.handle.stream.mmap.buf[i++];
}
if (c == '\r') {
if (file_handle.handle.stream.mmap.buf[i] == '\n') {
i++;
}
}
file_handle.handle.stream.mmap.buf += i;
file_handle.handle.stream.mmap.len -= i;
}
}
}
switch (behavior) {
case PHP_MODE_STANDARD:
php_execute_script(&file_handle TSRMLS_CC);
break;
case PHP_MODE_LINT:
PG(during_request_startup) = 0;
exit_status = php_lint_script(&file_handle TSRMLS_CC);
if (exit_status == SUCCESS) {
zend_printf("No syntax errors detected in %s\n", file_handle.filename);
} else {
zend_printf("Errors parsing %s\n", file_handle.filename);
}
break;
case PHP_MODE_STRIP:
if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) {
zend_strip(TSRMLS_C);
zend_file_handle_dtor(&file_handle TSRMLS_CC);
php_output_teardown();
}
return SUCCESS;
break;
case PHP_MODE_HIGHLIGHT:
{
zend_syntax_highlighter_ini syntax_highlighter_ini;
if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) {
php_get_highlight_struct(&syntax_highlighter_ini);
zend_highlight(&syntax_highlighter_ini TSRMLS_CC);
if (fastcgi) {
goto fastcgi_request_done;
}
zend_file_handle_dtor(&file_handle TSRMLS_CC);
php_output_teardown();
}
return SUCCESS;
}
break;
#if 0
/* Zeev might want to do something with this one day */
case PHP_MODE_INDENT:
open_file_for_scanning(&file_handle TSRMLS_CC);
zend_indent();
zend_file_handle_dtor(&file_handle TSRMLS_CC);
php_output_teardown();
return SUCCESS;
break;
#endif
}
fastcgi_request_done:
{
STR_FREE(SG(request_info).path_translated);
php_request_shutdown((void *) 0);
if (exit_status == 0) {
exit_status = EG(exit_status);
}
if (free_query_string && SG(request_info).query_string) {
free(SG(request_info).query_string);
SG(request_info).query_string = NULL;
}
}
if (!fastcgi) {
if (benchmark) {
repeats--;
if (repeats > 0) {
script_file = NULL;
php_optind = orig_optind;
php_optarg = orig_optarg;
continue;
}
}
break;
}
/* only fastcgi will get here */
requests++;
if (max_requests && (requests == max_requests)) {
fcgi_finish_request(request, 1);
if (bindpath) {
free(bindpath);
}
if (max_requests != 1) {
/* no need to return exit_status of the last request */
exit_status = 0;
}
break;
}
/* end of fastcgi loop */
}
if (request) {
fcgi_destroy_request(request);
}
fcgi_shutdown();
if (cgi_sapi_module.php_ini_path_override) {
free(cgi_sapi_module.php_ini_path_override);
}
if (cgi_sapi_module.ini_entries) {
free(cgi_sapi_module.ini_entries);
}
} zend_catch {
exit_status = 255;
} zend_end_try();
out:
if (benchmark) {
int sec;
#ifdef HAVE_GETTIMEOFDAY
int usec;
gettimeofday(&end, NULL);
sec = (int)(end.tv_sec - start.tv_sec);
if (end.tv_usec >= start.tv_usec) {
usec = (int)(end.tv_usec - start.tv_usec);
} else {
sec -= 1;
usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
}
fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
#else
time(&end);
sec = (int)(end - start);
fprintf(stderr, "\nElapsed time: %d sec\n", sec);
#endif
}
#ifndef PHP_WIN32
parent_out:
#endif
SG(server_context) = NULL;
php_module_shutdown(TSRMLS_C);
sapi_shutdown();
#ifdef ZTS
tsrm_shutdown();
#endif
#if defined(PHP_WIN32) && ZEND_DEBUG && 0
_CrtDumpMemoryLeaks();
#endif
return exit_status;
}
|
CWE-119
| 178,046 | 10,307 |
33381639658975017969612446643654148135
| null | null | null |
php
|
a72cd07f2983dc43a6bb35209dc4687852e53c09
| 1 |
apprentice_load(struct magic_set *ms, const char *fn, int action)
{
int errs = 0;
uint32_t i, j;
size_t files = 0, maxfiles = 0;
char **filearr = NULL;
struct stat st;
struct magic_map *map;
struct magic_entry_set mset[MAGIC_SETS];
php_stream *dir;
php_stream_dirent d;
TSRMLS_FETCH();
memset(mset, 0, sizeof(mset));
ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL)
{
file_oomem(ms, sizeof(*map));
return NULL;
}
/* print silly verbose header for USG compat. */
if (action == FILE_CHECK)
(void)fprintf(stderr, "%s\n", usg_hdr);
/* load directory or file */
/* FIXME: Read file names and sort them to prevent
non-determinism. See Debian bug #488562. */
if (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
int mflen;
char mfn[MAXPATHLEN];
dir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL);
if (!dir) {
errs++;
goto out;
}
while (php_stream_readdir(dir, &d)) {
if ((mflen = snprintf(mfn, sizeof(mfn), "%s/%s", fn, d.d_name)) < 0) {
file_oomem(ms,
strlen(fn) + strlen(d.d_name) + 2);
errs++;
php_stream_closedir(dir);
goto out;
}
if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
continue;
}
if (files >= maxfiles) {
size_t mlen;
maxfiles = (maxfiles + 1) * 2;
mlen = maxfiles * sizeof(*filearr);
if ((filearr = CAST(char **,
erealloc(filearr, mlen))) == NULL) {
file_oomem(ms, mlen);
efree(mfn);
php_stream_closedir(dir);
errs++;
goto out;
goto out;
}
}
filearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen);
}
php_stream_closedir(dir);
qsort(filearr, files, sizeof(*filearr), cmpstrp);
for (i = 0; i < files; i++) {
load_1(ms, action, filearr[i], &errs, mset);
efree(filearr[i]);
}
efree(filearr);
} else
load_1(ms, action, fn, &errs, mset);
if (errs)
goto out;
for (j = 0; j < MAGIC_SETS; j++) {
/* Set types of tests */
for (i = 0; i < mset[j].count; ) {
if (mset[j].me[i].mp->cont_level != 0) {
i++;
continue;
}
i = set_text_binary(ms, mset[j].me, mset[j].count, i);
}
qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
apprentice_sort);
/*
* Make sure that any level 0 "default" line is last
* (if one exists).
*/
set_last_default(ms, mset[j].me, mset[j].count);
/* coalesce per file arrays into a single one */
if (coalesce_entries(ms, mset[j].me, mset[j].count,
&map->magic[j], &map->nmagic[j]) == -1) {
errs++;
goto out;
}
}
out:
for (j = 0; j < MAGIC_SETS; j++)
magic_entry_free(mset[j].me, mset[j].count);
if (errs) {
for (j = 0; j < MAGIC_SETS; j++) {
if (map->magic[j])
efree(map->magic[j]);
}
efree(map);
return NULL;
}
return map;
}
|
CWE-17
| 178,054 | 10,308 |
3757341651210782745204748466497745440
| null | null | null |
php
|
2bcf69d073190e4f032d883f3416dea1b027a39e
| 1 |
ZEND_API void zend_ts_hash_graceful_destroy(TsHashTable *ht)
{
begin_write(ht);
zend_hash_graceful_destroy(TS_HASH(ht));
end_write(ht);
#ifdef ZTS
tsrm_mutex_free(ht->mx_reader);
tsrm_mutex_free(ht->mx_reader);
#endif
}
| 178,055 | 10,309 |
314250944240978907907972494924267065320
| null | null | null |
|
php
|
c818d0d01341907fee82bdb81cab07b7d93bb9db
| 1 |
static int date_from_ISO8601 (const char *text, time_t * value) {
struct tm tm;
* Begin Time Functions *
***********************/
static int date_from_ISO8601 (const char *text, time_t * value) {
struct tm tm;
int n;
int i;
char buf[18];
if (strchr (text, '-')) {
char *p = (char *) text, *p2 = buf;
}
if (*p != '-') {
*p2 = *p;
p2++;
}
p++;
}
}
|
CWE-119
| 178,061 | 10,310 |
123041013345562321718650352741660412700
| null | null | null |
php
|
630f9c33c23639de85c3fd306b209b538b73b4c9
| 1 |
static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
while (elements-- > 0) {
zval *key, *data, **old_data;
ALLOC_INIT_ZVAL(key);
if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
ALLOC_INIT_ZVAL(data);
if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
zval_dtor(data);
FREE_ZVAL(data);
return 0;
}
if (!objprops) {
switch (Z_TYPE_P(key)) {
case IS_LONG:
if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
break;
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
break;
}
} else {
/* object properties should include no integers */
convert_to_string(key);
zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
sizeof data, NULL);
}
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
| 178,065 | 10,312 |
200956999623139778733498138642720342949
| null | null | null |
|
qemu
|
4774718e5c194026ba5ee7a28d9be49be3080e42
| 1 |
void v9fs_device_unrealize_common(V9fsState *s, Error **errp)
{
g_free(s->ctx.fs_root);
g_free(s->tag);
}
|
CWE-400
| 178,068 | 10,314 |
286237426367056739379767787095864223086
| null | null | null |
qemu
|
e6908bfe8e07f2b452e78e677da1b45b1c0f6829
| 1 |
static void set_pixel_format(VncState *vs,
int bits_per_pixel, int depth,
int big_endian_flag, int true_color_flag,
int red_max, int green_max, int blue_max,
int red_shift, int green_shift, int blue_shift)
{
if (!true_color_flag) {
vnc_client_error(vs);
return;
}
vs->client_pf.rmax = red_max;
vs->client_pf.rbits = hweight_long(red_max);
vs->client_pf.rshift = red_shift;
vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
vs->client_be = big_endian_flag;
set_pixel_conversion(vs);
graphic_hw_invalidate(NULL);
graphic_hw_update(NULL);
}
|
CWE-264
| 178,074 | 10,315 |
146296147133883449923700242312037223572
| null | null | null |
qemu
|
fdfcc9aeea1492f4b819a24c94dfb678145b1bf9
| 1 |
static void coroutine_fn v9fs_write(void *opaque)
{
ssize_t err;
int32_t fid;
uint64_t off;
uint32_t count;
int32_t len = 0;
int32_t total = 0;
size_t offset = 7;
V9fsFidState *fidp;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
QEMUIOVector qiov_full;
QEMUIOVector qiov;
err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count);
if (err < 0) {
pdu_complete(pdu, err);
return;
}
offset += err;
v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true);
trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov);
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
if (fidp->fid_type == P9_FID_FILE) {
if (fidp->fs.fd == -1) {
err = -EINVAL;
goto out;
}
} else if (fidp->fid_type == P9_FID_XATTR) {
/*
* setxattr operation
*/
err = v9fs_xattr_write(s, pdu, fidp, off, count,
qiov_full.iov, qiov_full.niov);
goto out;
} else {
err = -EINVAL;
goto out;
}
qemu_iovec_init(&qiov, qiov_full.niov);
do {
qemu_iovec_reset(&qiov);
qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total);
if (0) {
print_sg(qiov.iov, qiov.niov);
}
/* Loop in case of EINTR */
do {
len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off);
if (len >= 0) {
off += len;
total += len;
}
} while (len == -EINTR && !pdu->cancelled);
if (len < 0) {
/* IO error return the error */
err = len;
goto out_qiov;
}
} while (total < count && len > 0);
offset = 7;
err = pdu_marshal(pdu, offset, "d", total);
if (err < 0) {
goto out;
}
err += offset;
trace_v9fs_write_return(pdu->tag, pdu->id, total, err);
out_qiov:
qemu_iovec_destroy(&qiov);
out:
put_fid(pdu, fidp);
out_nofid:
qemu_iovec_destroy(&qiov_full);
pdu_complete(pdu, err);
}
|
CWE-399
| 178,078 | 10,316 |
314966331196208321845236263387484737503
| null | null | null |
qemu
|
4c1586787ff43c9acd18a56c12d720e3e6be9f7c
| 1 |
static void coroutine_fn v9fs_link(void *opaque)
{
V9fsPDU *pdu = opaque;
int32_t dfid, oldfid;
V9fsFidState *dfidp, *oldfidp;
V9fsString name;
size_t offset = 7;
int err = 0;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);
if (name_is_illegal(name.data)) {
err = -ENOENT;
goto out_nofid;
}
if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
err = -EEXIST;
goto out_nofid;
}
dfidp = get_fid(pdu, dfid);
if (dfidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
oldfidp = get_fid(pdu, oldfid);
if (oldfidp == NULL) {
err = -ENOENT;
goto out;
}
err = v9fs_co_link(pdu, oldfidp, dfidp, &name);
if (!err) {
err = offset;
}
out:
put_fid(pdu, dfidp);
out_nofid:
pdu_complete(pdu, err);
}
|
CWE-399
| 178,079 | 10,317 |
20182681944381355439749054301956657816
| null | null | null |
qemu
|
eb687602853b4ae656e9236ee4222609f3a6887d
| 1 |
static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc(size);
err = offset;
put_fid(pdu, file_fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
|
CWE-119
| 178,080 | 10,318 |
69981629644997296175453657460481062076
| null | null | null |
qemu
|
ff55e94d23ae94c8628b0115320157c763eb3e06
| 1 |
static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc0(size);
err = offset;
put_fid(pdu, file_fidp);
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
|
CWE-399
| 178,081 | 10,319 |
6911755873108184268982541483346237189
| null | null | null |
libx11
|
8c29f1607a31dac0911e45a0dd3d74173822b3c9
| 1 |
XListFonts(
register Display *dpy,
_Xconst char *pattern, /* null-terminated */
int maxNames,
int *actualCount) /* RETURN */
{
register long nbytes;
register unsigned i;
register int length;
char **flist = NULL;
char *ch = NULL;
char *chend;
int count = 0;
xListFontsReply rep;
register xListFontsReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetReq(ListFonts, req);
req->maxNames = maxNames;
nbytes = req->nbytes = pattern ? strlen (pattern) : 0;
req->length += (nbytes + 3) >> 2;
_XSend (dpy, pattern, nbytes);
/* use _XSend instead of Data, since following _XReply will flush buffer */
if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nFonts) {
flist = Xmalloc (rep.nFonts * sizeof(char *));
if (rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc(rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + (rlen + 1);
length = *(unsigned char *)ch;
*ch = 1; /* make sure it is non-zero for XFreeFontNames */
for (i = 0; i < rep.nFonts; i++) {
if (ch + length < chend) {
flist[i] = ch + 1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else
flist[i] = NULL;
}
}
*actualCount = count;
for (names = list+1; *names; names++)
Xfree (*names);
}
|
CWE-787
| 178,095 | 10,320 |
84930321502000240747350975913673394792
| null | null | null |
qemu
|
670e56d3ed2918b3861d9216f2c0540d9e9ae0d5
| 1 |
static int mptsas_process_scsi_io_request(MPTSASState *s,
MPIMsgSCSIIORequest *scsi_io,
hwaddr addr)
{
MPTSASRequest *req;
MPIMsgSCSIIOReply reply;
SCSIDevice *sdev;
int status;
mptsas_fix_scsi_io_endianness(scsi_io);
trace_mptsas_process_scsi_io_request(s, scsi_io->Bus, scsi_io->TargetID,
scsi_io->LUN[1], scsi_io->DataLength);
status = mptsas_scsi_device_find(s, scsi_io->Bus, scsi_io->TargetID,
scsi_io->LUN, &sdev);
if (status) {
goto bad;
}
req = g_new(MPTSASRequest, 1);
QTAILQ_INSERT_TAIL(&s->pending, req, next);
req->scsi_io = *scsi_io;
req->dev = s;
status = mptsas_build_sgl(s, req, addr);
if (status) {
goto free_bad;
}
if (req->qsg.size < scsi_io->DataLength) {
trace_mptsas_sgl_overflow(s, scsi_io->MsgContext, scsi_io->DataLength,
req->qsg.size);
status = MPI_IOCSTATUS_INVALID_SGL;
goto free_bad;
}
req->sreq = scsi_req_new(sdev, scsi_io->MsgContext,
scsi_io->LUN[1], scsi_io->CDB, req);
if (req->sreq->cmd.xfer > scsi_io->DataLength) {
goto overrun;
}
switch (scsi_io->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK) {
case MPI_SCSIIO_CONTROL_NODATATRANSFER:
if (req->sreq->cmd.mode != SCSI_XFER_NONE) {
goto overrun;
}
break;
case MPI_SCSIIO_CONTROL_WRITE:
if (req->sreq->cmd.mode != SCSI_XFER_TO_DEV) {
goto overrun;
}
break;
case MPI_SCSIIO_CONTROL_READ:
if (req->sreq->cmd.mode != SCSI_XFER_FROM_DEV) {
goto overrun;
}
break;
}
if (scsi_req_enqueue(req->sreq)) {
scsi_req_continue(req->sreq);
}
return 0;
overrun:
trace_mptsas_scsi_overflow(s, scsi_io->MsgContext, req->sreq->cmd.xfer,
scsi_io->DataLength);
status = MPI_IOCSTATUS_SCSI_DATA_OVERRUN;
free_bad:
mptsas_free_request(req);
bad:
memset(&reply, 0, sizeof(reply));
reply.TargetID = scsi_io->TargetID;
reply.Bus = scsi_io->Bus;
reply.MsgLength = sizeof(reply) / 4;
reply.Function = scsi_io->Function;
reply.CDBLength = scsi_io->CDBLength;
reply.SenseBufferLength = scsi_io->SenseBufferLength;
reply.MsgContext = scsi_io->MsgContext;
reply.SCSIState = MPI_SCSI_STATE_NO_SCSI_STATUS;
reply.IOCStatus = status;
mptsas_fix_scsi_io_reply_endianness(&reply);
mptsas_reply(s, (MPIDefaultReply *)&reply);
return 0;
}
|
CWE-787
| 178,100 | 10,322 |
199184606857264200017307255213404625984
| null | null | null |
qemu
|
d251157ac1928191af851d199a9ff255d330bec9
| 1 |
pvscsi_ring_pop_req_descr(PVSCSIRingInfo *mgr)
{
uint32_t ready_ptr = RS_GET_FIELD(mgr, reqProdIdx);
if (ready_ptr != mgr->consumed_ptr) {
uint32_t next_ready_ptr =
mgr->consumed_ptr++ & mgr->txr_len_mask;
uint32_t next_ready_page =
return mgr->req_ring_pages_pa[next_ready_page] +
inpage_idx * sizeof(PVSCSIRingReqDesc);
} else {
return 0;
}
}
|
CWE-399
| 178,101 | 10,323 |
141291229922936327399262675900654216459
| null | null | null |
qemu
|
a0d1cbdacff5df4ded16b753b38fdd9da6092968
| 1 |
static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
{
struct xlx_ethlite *s = qemu_get_nic_opaque(nc);
unsigned int rxbase = s->rxbuf * (0x800 / 4);
/* DA filter. */
if (!(buf[0] & 0x80) && memcmp(&s->conf.macaddr.a[0], buf, 6))
return size;
if (s->regs[rxbase + R_RX_CTRL0] & CTRL_S) {
D(qemu_log("ethlite lost packet %x\n", s->regs[R_RX_CTRL0]));
return -1;
}
D(qemu_log("%s %zd rxbase=%x\n", __func__, size, rxbase));
memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size);
s->regs[rxbase + R_RX_CTRL0] |= CTRL_S;
/* If c_rx_pingpong was set flip buffers. */
s->rxbuf ^= s->c_rx_pingpong;
return size;
}
|
CWE-119
| 178,105 | 10,324 |
79108392566906662649752952158580972366
| null | null | null |
qemu
|
65a8e1f6413a0f6f79894da710b5d6d43361d27d
| 1 |
size_t mptsas_config_ioc_0(MPTSASState *s, uint8_t **data, int address)
{
PCIDeviceClass *pcic = PCI_DEVICE_GET_CLASS(s);
return MPTSAS_CONFIG_PACK(0, MPI_CONFIG_PAGETYPE_IOC, 0x01,
"*l*lwwb*b*b*blww",
pcic->vendor_id, pcic->device_id, pcic->revision,
pcic->subsystem_vendor_id,
pcic->subsystem_id);
}
|
CWE-20
| 178,106 | 10,325 |
222774731993991100736489546867888744653
| null | null | null |
qemu
|
65a8e1f6413a0f6f79894da710b5d6d43361d27d
| 1 |
size_t mptsas_config_manufacturing_1(MPTSASState *s, uint8_t **data, int address)
{
/* VPD - all zeros */
return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_MANUFACTURING, 0x00,
"s256");
}
|
CWE-20
| 178,107 | 10,326 |
172679888862406933067398122810254151279
| null | null | null |
qemu
|
49adc5d3f8c6bb75e55ebfeab109c5c37dea65e8
| 1 |
pvscsi_convert_sglist(PVSCSIRequest *r)
{
int chunk_size;
uint64_t data_length = r->req.dataLen;
PVSCSISGState sg = r->sg;
while (data_length) {
while (!sg.resid) {
pvscsi_get_next_sg_elem(&sg);
trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr,
r->sg.resid);
}
assert(data_length > 0);
chunk_size = MIN((unsigned) data_length, sg.resid);
if (chunk_size) {
qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size);
}
sg.dataAddr += chunk_size;
data_length -= chunk_size;
sg.resid -= chunk_size;
}
}
|
CWE-399
| 178,108 | 10,327 |
322869563713856932315642215321382715657
| null | null | null |
qemu
|
7f61f4690dd153be98900a2a508b88989e692753
| 1 |
pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri)
{
int i;
uint32_t txr_len_log2, rxr_len_log2;
uint32_t req_ring_size, cmp_ring_size;
m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT;
if ((ri->reqRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)
|| (ri->cmpRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)) {
return -1;
}
req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE;
txr_len_log2 = pvscsi_log2(req_ring_size - 1);
}
|
CWE-125
| 178,109 | 10,328 |
238500594215988308702267189774691121707
| null | null | null |
qemu
|
47882fa4975bf0b58dd74474329fdd7154e8f04c
| 1 |
void net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev,
uint32_t max_frags, bool has_virt_hdr)
{
struct NetTxPkt *p = g_malloc0(sizeof *p);
p->pci_dev = pci_dev;
p->vec = g_malloc((sizeof *p->vec) *
(max_frags + NET_TX_PKT_PL_START_FRAG));
p->raw = g_malloc((sizeof *p->raw) * max_frags);
p->max_payload_frags = max_frags;
p->max_raw_frags = max_frags;
p->max_raw_frags = max_frags;
p->has_virt_hdr = has_virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_len =
p->has_virt_hdr ? sizeof p->virt_hdr : 0;
p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr;
p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr;
*pkt = p;
}
|
CWE-190
| 178,119 | 10,331 |
319929679670743224123794393862534160224
| null | null | null |
qemu
|
fdda170e50b8af062cf5741e12c4fb5e57a2eacf
| 1 |
static void vmxnet3_complete_packet(VMXNET3State *s, int qidx, uint32_t tx_ridx)
{
struct Vmxnet3_TxCompDesc txcq_descr;
PCIDevice *d = PCI_DEVICE(s);
VMXNET3_RING_DUMP(VMW_RIPRN, "TXC", qidx, &s->txq_descr[qidx].comp_ring);
txcq_descr.txdIdx = tx_ridx;
txcq_descr.gen = vmxnet3_ring_curr_gen(&s->txq_descr[qidx].comp_ring);
/* Flush changes in TX descriptor before changing the counter value */
smp_wmb();
vmxnet3_inc_tx_completion_counter(s, qidx);
vmxnet3_trigger_interrupt(s, s->txq_descr[qidx].intr_idx);
}
|
CWE-200
| 178,120 | 10,332 |
261251614138140691061136061213158669100
| null | null | null |
qemu
|
ead315e43ea0c2ca3491209c6c8db8ce3f2bbe05
| 1 |
static bool net_tx_pkt_do_sw_fragmentation(struct NetTxPkt *pkt,
NetClientState *nc)
{
struct iovec fragment[NET_MAX_FRAG_SG_LIST];
size_t fragment_len = 0;
bool more_frags = false;
/* some pointers for shorter code */
void *l2_iov_base, *l3_iov_base;
size_t l2_iov_len, l3_iov_len;
int src_idx = NET_TX_PKT_PL_START_FRAG, dst_idx;
size_t src_offset = 0;
size_t fragment_offset = 0;
l2_iov_base = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_base;
l2_iov_len = pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_len;
l3_iov_base = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base;
l3_iov_len = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len;
/* Copy headers */
fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_base = l2_iov_base;
fragment[NET_TX_PKT_FRAGMENT_L2_HDR_POS].iov_len = l2_iov_len;
fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_base = l3_iov_base;
fragment[NET_TX_PKT_FRAGMENT_L3_HDR_POS].iov_len = l3_iov_len;
/* Put as much data as possible and send */
do {
fragment_len = net_tx_pkt_fetch_fragment(pkt, &src_idx, &src_offset,
fragment, &dst_idx);
more_frags = (fragment_offset + fragment_len < pkt->payload_len);
eth_setup_ip4_fragmentation(l2_iov_base, l2_iov_len, l3_iov_base,
l3_iov_len, fragment_len, fragment_offset, more_frags);
eth_fix_ip4_checksum(l3_iov_base, l3_iov_len);
net_tx_pkt_sendv(pkt, nc, fragment, dst_idx);
fragment_offset += fragment_len;
} while (more_frags);
return true;
}
|
CWE-399
| 178,124 | 10,333 |
235520435264538303396124933487436136561
| null | null | null |
qemu
|
6c352ca9b4ee3e1e286ea9e8434bd8e69ac7d0d8
| 1 |
vmxnet3_io_bar0_write(void *opaque, hwaddr addr,
uint64_t val, unsigned size)
{
VMXNET3State *s = opaque;
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_TXPROD,
VMXNET3_DEVICE_MAX_TX_QUEUES, VMXNET3_REG_ALIGN)) {
int tx_queue_idx =
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_IMR,
VMXNET3_MAX_INTRS, VMXNET3_REG_ALIGN)) {
int l = VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_IMR,
VMXNET3_REG_ALIGN);
VMW_CBPRN("Interrupt mask for line %d written: 0x%" PRIx64, l, val);
vmxnet3_on_interrupt_mask_changed(s, l, val);
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD,
VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN) ||
VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD2,
VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN)) {
return;
}
VMW_WRPRN("BAR0 unknown write [%" PRIx64 "] = %" PRIx64 ", size %d",
(uint64_t) addr, val, size);
}
|
CWE-416
| 178,125 | 10,334 |
108629993120341803762603906492132915657
| null | null | null |
qemu
|
926cde5f3e4d2504ed161ed0cb771ac7cad6fd11
| 1 |
static void esp_do_dma(ESPState *s)
{
uint32_t len;
int to_device;
len = s->dma_left;
if (s->do_cmd) {
trace_esp_do_dma(s->cmdlen, len);
s->dma_memory_read(s->dma_opaque, &s->cmdbuf[s->cmdlen], len);
return;
}
return;
}
|
CWE-787
| 178,133 | 10,335 |
315645112648473790512625990144427128450
| null | null | null |
php
|
81406c0c1d45f75fcc7972ed974d2597abb0b9e9
| 1 |
php_stream *php_stream_zip_opener(php_stream_wrapper *wrapper,
char *path,
char *mode,
int options,
char **opened_path,
php_stream_context *context STREAMS_DC TSRMLS_DC)
{
int path_len;
char *file_basename;
size_t file_basename_len;
char file_dirname[MAXPATHLEN];
struct zip *za;
struct zip_file *zf = NULL;
char *fragment;
int fragment_len;
int err;
php_stream *stream = NULL;
struct php_zip_stream_data_t *self;
fragment = strchr(path, '#');
if (!fragment) {
return NULL;
}
if (strncasecmp("zip://", path, 6) == 0) {
path += 6;
}
fragment_len = strlen(fragment);
if (fragment_len < 1) {
return NULL;
}
path_len = strlen(path);
if (path_len >= MAXPATHLEN || mode[0] != 'r') {
return NULL;
}
memcpy(file_dirname, path, path_len - fragment_len);
file_dirname[path_len - fragment_len] = '\0';
php_basename(path, path_len - fragment_len, NULL, 0, &file_basename, &file_basename_len TSRMLS_CC);
fragment++;
if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) {
efree(file_basename);
return NULL;
}
za = zip_open(file_dirname, ZIP_CREATE, &err);
if (za) {
zf = zip_fopen(za, fragment, 0);
if (zf) {
self = emalloc(sizeof(*self));
self->za = za;
self->zf = zf;
self->stream = NULL;
self->cursor = 0;
stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode);
if (opened_path) {
*opened_path = estrdup(path);
}
} else {
zip_close(za);
}
}
efree(file_basename);
if (!stream) {
return NULL;
} else {
return stream;
}
}
|
CWE-119
| 178,141 | 10,337 |
86278437795554756494309787707537290482
| null | null | null |
php
|
3798eb6fd5dddb211b01d41495072fd9858d4e32
| 1 |
PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */
{
const char *p;
char *name;
const char *endptr = val + vallen;
zval *current;
int namelen;
int has_value;
php_unserialize_data_t var_hash;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
for (p = val; p < endptr; ) {
zval **tmp;
namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF);
if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) {
return FAILURE;
}
name = estrndup(p + 1, namelen);
p += namelen + 1;
if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) {
if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) {
efree(name);
continue;
}
}
if (has_value) {
ALLOC_INIT_ZVAL(current);
if (php_var_unserialize(¤t, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) {
php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC);
} else {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return FAILURE;
}
var_push_dtor_no_addref(&var_hash, ¤t);
}
PS_ADD_VARL(name, namelen);
efree(name);
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
|
CWE-416
| 178,153 | 10,349 |
321421786241676728897157894496245899298
| null | null | null |
qemu
|
33243031dad02d161225ba99d782616da133f689
| 1 |
static void virgl_resource_attach_backing(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
{
struct virtio_gpu_resource_attach_backing att_rb;
struct iovec *res_iovs;
int ret;
VIRTIO_GPU_FILL_CMD(att_rb);
trace_virtio_gpu_cmd_res_back_attach(att_rb.resource_id);
ret = virtio_gpu_create_mapping_iov(&att_rb, cmd, NULL, &res_iovs);
if (ret != 0) {
cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
return;
}
virgl_renderer_resource_attach_iov(att_rb.resource_id,
res_iovs, att_rb.nr_entries);
}
|
CWE-772
| 178,160 | 10,352 |
17429442156578744716412782982661871687
| null | null | null |
exempi
|
aabedb5e749dd59112a3fe1e8e08f2d934f56666
| 1 |
VP8XChunk::VP8XChunk(Container* parent)
: Chunk(parent, kChunk_VP8X)
{
this->needsRewrite = true;
this->size = 10;
this->data.resize(this->size);
this->data.assign(this->size, 0);
XMP_Uns8* bitstream =
(XMP_Uns8*)parent->chunks[WEBP_CHUNK_IMAGE][0]->data.data();
XMP_Uns32 width = ((bitstream[7] << 8) | bitstream[6]) & 0x3fff;
XMP_Uns32 height = ((bitstream[9] << 8) | bitstream[8]) & 0x3fff;
this->width(width);
this->height(height);
parent->vp8x = this;
VP8XChunk::VP8XChunk(Container* parent, WEBP_MetaHandler* handler)
: Chunk(parent, handler)
{
this->size = 10;
this->needsRewrite = true;
parent->vp8x = this;
}
XMP_Uns32 VP8XChunk::width()
{
return GetLE24(&this->data[4]) + 1;
}
void VP8XChunk::width(XMP_Uns32 val)
{
PutLE24(&this->data[4], val > 0 ? val - 1 : 0);
}
XMP_Uns32 VP8XChunk::height()
{
return GetLE24(&this->data[7]) + 1;
}
void VP8XChunk::height(XMP_Uns32 val)
{
PutLE24(&this->data[7], val > 0 ? val - 1 : 0);
}
bool VP8XChunk::xmp()
{
XMP_Uns32 flags = GetLE32(&this->data[0]);
return (bool)((flags >> XMP_FLAG_BIT) & 1);
}
void VP8XChunk::xmp(bool hasXMP)
{
XMP_Uns32 flags = GetLE32(&this->data[0]);
flags ^= (-hasXMP ^ flags) & (1 << XMP_FLAG_BIT);
PutLE32(&this->data[0], flags);
}
Container::Container(WEBP_MetaHandler* handler) : Chunk(NULL, handler)
{
this->needsRewrite = false;
XMP_IO* file = handler->parent->ioRef;
file->Seek(12, kXMP_SeekFromStart);
XMP_Int64 size = handler->initialFileSize;
XMP_Uns32 peek = 0;
while (file->Offset() < size) {
peek = XIO::PeekUns32_LE(file);
switch (peek) {
case kChunk_XMP_:
this->addChunk(new XMPChunk(this, handler));
break;
case kChunk_VP8X:
this->addChunk(new VP8XChunk(this, handler));
break;
default:
this->addChunk(new Chunk(this, handler));
break;
}
}
if (this->chunks[WEBP_CHUNK_IMAGE].size() == 0) {
XMP_Throw("File has no image bitstream", kXMPErr_BadFileFormat);
}
if (this->chunks[WEBP_CHUNK_VP8X].size() == 0) {
this->needsRewrite = true;
this->addChunk(new VP8XChunk(this));
}
if (this->chunks[WEBP_CHUNK_XMP].size() == 0) {
XMPChunk* xmpChunk = new XMPChunk(this);
this->addChunk(xmpChunk);
handler->xmpChunk = xmpChunk;
this->vp8x->xmp(true);
}
}
Chunk* Container::getExifChunk()
{
if (this->chunks[WEBP::WEBP_CHUNK_EXIF].size() == 0) {
return NULL;
}
return this->chunks[WEBP::WEBP_CHUNK_EXIF][0];
}
void Container::addChunk(Chunk* chunk)
{
ChunkId idx;
try {
idx = chunkMap.at(chunk->tag);
}
catch (const std::out_of_range& e) {
idx = WEBP_CHUNK_UNKNOWN;
}
this->chunks[idx].push_back(chunk);
}
void Container::write(WEBP_MetaHandler* handler)
{
XMP_IO* file = handler->parent->ioRef;
file->Rewind();
XIO::WriteUns32_LE(file, this->tag);
XIO::WriteUns32_LE(file, (XMP_Uns32) this->size);
XIO::WriteUns32_LE(file, kChunk_WEBP);
size_t i, j;
std::vector<Chunk*> chunkVect;
for (i = 0; i < WEBP_CHUNK_NIL; i++) {
chunkVect = this->chunks[i];
for (j = 0; j < chunkVect.size(); j++) {
chunkVect.at(j)->write(handler);
}
}
XMP_Int64 lastOffset = file->Offset();
this->size = lastOffset - 8;
file->Seek(this->pos + 4, kXMP_SeekFromStart);
XIO::WriteUns32_LE(file, (XMP_Uns32) this->size);
file->Seek(lastOffset, kXMP_SeekFromStart);
if (lastOffset < handler->initialFileSize) {
file->Truncate(lastOffset);
}
}
Container::~Container()
{
Chunk* chunk;
size_t i;
std::vector<Chunk*> chunkVect;
for (i = 0; i < WEBP_CHUNK_NIL; i++) {
chunkVect = this->chunks[i];
while (!chunkVect.empty()) {
chunk = chunkVect.back();
delete chunk;
chunkVect.pop_back();
}
}
}
}
|
CWE-476
| 178,165 | 10,353 |
42743116564619947533645887795974573050
| null | null | null |
exempi
|
6cbd34025e5fd3ba47b29b602096e456507ce83b
| 1 |
void PSIR_FileWriter::ParseFileResources ( XMP_IO* fileRef, XMP_Uns32 length )
{
static const size_t kMinPSIRSize = 12; // 4+2+1+1+4
this->DeleteExistingInfo();
this->fileParsed = true;
if ( length == 0 ) return;
XMP_Int64 psirOrigin = fileRef->Offset(); // Need this to determine the resource data offsets.
XMP_Int64 fileEnd = psirOrigin + length;
char nameBuffer [260]; // The name is a PString, at 1+255+1 including length and pad.
while ( fileRef->Offset() < fileEnd ) {
if ( ! XIO::CheckFileSpace ( fileRef, kMinPSIRSize ) ) break; // Bad image resource.
XMP_Int64 thisRsrcPos = fileRef->Offset();
XMP_Uns32 type = XIO::ReadUns32_BE ( fileRef );
XMP_Uns16 id = XIO::ReadUns16_BE ( fileRef );
XMP_Uns8 nameLen = XIO::ReadUns8 ( fileRef ); // ! The length for the Pascal string.
XMP_Uns16 paddedLen = (nameLen + 2) & 0xFFFE; // ! Round up to an even total. Yes, +2!
if ( ! XIO::CheckFileSpace ( fileRef, paddedLen+4 ) ) break; // Bad image resource.
nameBuffer[0] = nameLen;
fileRef->ReadAll ( &nameBuffer[1], paddedLen-1 ); // Include the pad byte, present for zero nameLen.
XMP_Uns32 dataLen = XIO::ReadUns32_BE ( fileRef );
XMP_Uns32 dataTotal = ((dataLen + 1) & 0xFFFFFFFEUL); // Round up to an even total.
if ( ! XIO::CheckFileSpace ( fileRef, dataTotal ) ) break; // Bad image resource.
XMP_Int64 thisDataPos = fileRef->Offset();
continue;
}
InternalRsrcInfo newInfo ( id, dataLen, kIsFileBased );
InternalRsrcMap::iterator rsrcPos = this->imgRsrcs.find ( id );
if ( rsrcPos == this->imgRsrcs.end() ) {
rsrcPos = this->imgRsrcs.insert ( rsrcPos, InternalRsrcMap::value_type ( id, newInfo ) );
} else if ( (rsrcPos->second.dataLen == 0) && (newInfo.dataLen != 0) ) {
rsrcPos->second = newInfo;
} else {
fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart );
continue;
}
InternalRsrcInfo* rsrcPtr = &rsrcPos->second;
rsrcPtr->origOffset = (XMP_Uns32)thisDataPos;
if ( nameLen > 0 ) {
rsrcPtr->rsrcName = (XMP_Uns8*) malloc ( paddedLen );
if ( rsrcPtr->rsrcName == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory );
memcpy ( (void*)rsrcPtr->rsrcName, nameBuffer, paddedLen ); // AUDIT: Safe, allocated enough bytes above.
}
if ( ! IsMetadataImgRsrc ( id ) ) {
fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart );
continue;
}
rsrcPtr->dataPtr = malloc ( dataTotal ); // ! Allocate after the IsMetadataImgRsrc check.
if ( rsrcPtr->dataPtr == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory );
fileRef->ReadAll ( (void*)rsrcPtr->dataPtr, dataTotal );
}
|
CWE-125
| 178,166 | 10,354 |
193473072449410278157936971956966923614
| null | null | null |
exempi
|
baa4b8a02c1ffab9645d13f0bfb1c0d10d311a0c
| 1 |
void PostScript_MetaHandler::ParsePSFile()
{
bool found = false;
IOBuffer ioBuf;
XMP_IO* fileRef = this->parent->ioRef;
XMP_AbortProc abortProc = this->parent->abortProc;
void * abortArg = this->parent->abortArg;
const bool checkAbort = (abortProc != 0);
if ( ! PostScript_Support::IsValidPSFile(fileRef,this->fileformat) ) return ;
fileRef->Rewind();
if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ;
XMP_Uns32 fileheader = GetUns32BE ( ioBuf.ptr );
if ( fileheader == 0xC5D0D3C6 )
{
if ( ! CheckFileSpace ( fileRef, &ioBuf, 30 ) ) return ;
XMP_Uns32 psOffset = GetUns32LE ( ioBuf.ptr+4 ); // PostScript offset.
XMP_Uns32 psLength = GetUns32LE ( ioBuf.ptr+8 ); // PostScript length.
setTokenInfo(kPS_EndPostScript,psOffset+psLength,0);
MoveToOffset ( fileRef, psOffset, &ioBuf );
}
while ( true )
{
if ( checkAbort && abortProc(abortArg) ) {
XMP_Throw ( "PostScript_MetaHandler::FindPostScriptHint - User abort", kXMPErr_UserAbort );
}
if ( ! CheckFileSpace ( fileRef, &ioBuf, kPSContainsForString.length() ) ) return ;
if ( (CheckFileSpace ( fileRef, &ioBuf, kPSEndCommentString.length() )&&
CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSEndCommentString.c_str()), kPSEndCommentString.length() )
)|| *ioBuf.ptr!='%' || !(*(ioBuf.ptr+1)>32 && *(ioBuf.ptr+1)<=126 )) // implicit endcomment check
{
if (CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSEndCommentString.c_str()), kPSEndCommentString.length() ))
{
setTokenInfo(kPS_EndComments,ioBuf.filePos+ioBuf.ptr-ioBuf.data,kPSEndCommentString.length());
ioBuf.ptr+=kPSEndCommentString.length();
}
else
{
setTokenInfo(kPS_EndComments,ioBuf.filePos+ioBuf.ptr-ioBuf.data,0);
}
while(true)
{
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ;
if (! IsWhitespace (*ioBuf.ptr)) break;
++ioBuf.ptr;
}
while(true)
{
if ( ! CheckFileSpace ( fileRef, &ioBuf, 5 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("/DOCI"), 5 )
&& CheckFileSpace ( fileRef, &ioBuf, kPSContainsDocInfoString.length() )
&&CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsDocInfoString.c_str()), kPSContainsDocInfoString.length() ))
{
ioBuf.ptr+=kPSContainsDocInfoString.length();
ExtractDocInfoDict(ioBuf);
}// DOCINFO Not found in document
else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Beg"), 5 ))
{//possibly one of %%BeginProlog %%BeginSetup %%BeginBinary %%BeginData
XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data;
ioBuf.ptr+=5;
if (!CheckFileSpace ( fileRef, &ioBuf, 6 )) return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("inProl"), 6 ))
{//%%BeginProlog
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 2 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("og"), 2 ))
{
ioBuf.ptr+=2;
setTokenInfo(kPS_BeginProlog,begStartpos,13);
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inSetu"), 6 ))
{//%%BeginSetup
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 1 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("p"), 1 ))
{
ioBuf.ptr+=1;
setTokenInfo(kPS_BeginSetup,begStartpos,12);
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inBina"), 6 ))
{//%%BeginBinary
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 3 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("ry"), 3 ))
{
ioBuf.ptr+=3;
while(true)
{
if (!CheckFileSpace ( fileRef, &ioBuf, 12 ))return;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndBinary"), 11 ))
{
ioBuf.ptr+=11;
if (IsWhitespace(*ioBuf.ptr))
{
ioBuf.ptr++;
break;
}
}
++ioBuf.ptr;
}
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inData"), 6 ))
{//%%BeginData
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 1 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr(":"), 1 ))
{
while(true)
{
if (!CheckFileSpace ( fileRef, &ioBuf, 10 ))return;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndData"), 9 ))
{
ioBuf.ptr+=9;
if (IsWhitespace(*ioBuf.ptr))
{
ioBuf.ptr++;
break;
}
}
++ioBuf.ptr;
}
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inDocu"), 6 ))
{// %%BeginDocument
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 5 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("ment:"), 5 ))
{
ioBuf.ptr+=5;
while(true)
{
if (!CheckFileSpace ( fileRef, &ioBuf, 14 ))return;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndDocument"), 13 ))
{
ioBuf.ptr+=13;
if (IsWhitespace(*ioBuf.ptr))
{
ioBuf.ptr++;
break;
}
}
++ioBuf.ptr;
}
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inPage"), 6 ))
{// %%BeginPageSetup
ioBuf.ptr+=6;
if (!CheckFileSpace ( fileRef, &ioBuf, 5 ))return;
if(CheckBytes ( ioBuf.ptr, Uns8Ptr("Setup"), 5 ))
{
ioBuf.ptr+=5;
setTokenInfo(kPS_BeginPageSetup,begStartpos,16);
}
}
}
else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%End"), 5 ))
{//possibly %%EndProlog %%EndSetup %%EndPageSetup %%EndPageComments
XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data;
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 5 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("Prolo"), 5 ))
{// %%EndProlog
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("g"), 1 ))
{
ioBuf.ptr+=1;
setTokenInfo(kPS_EndProlog,begStartpos,11);
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("Setup"), 5 ))
{//%%EndSetup
ioBuf.ptr+=5;
setTokenInfo(kPS_EndSetup,begStartpos,10);
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("PageS"), 5 ))
{//%%EndPageSetup
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("etup"), 4 ))
{
ioBuf.ptr+=4;
setTokenInfo(kPS_EndPageSetup,begStartpos,14);
}
}
else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("PageC"), 5 ))
{//%%EndPageComments
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 7 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("omments"), 7 ))
{
ioBuf.ptr+=7;
setTokenInfo(kPS_EndPageComments,begStartpos,17);
}
}
}
else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Pag"), 5 ))
{
XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data;
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 2 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr(":"), 2 ))
{
ioBuf.ptr+=2;
while(!IsNewline(*ioBuf.ptr))
{
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ;
++ioBuf.ptr;
}
setTokenInfo(kPS_Page,begStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-begStartpos);
}
}
else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Tra"), 5 ))
{
XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data;
ioBuf.ptr+=5;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ;
if (CheckBytes ( ioBuf.ptr, Uns8Ptr("iler"), 4 ))
{
ioBuf.ptr+=4;
while(!IsNewline(*ioBuf.ptr)) ++ioBuf.ptr;
setTokenInfo(kPS_Trailer,begStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-begStartpos);
}
}
ioBuf.ptr+=5;
setTokenInfo(kPS_EOF,ioBuf.filePos+ioBuf.ptr-ioBuf.data,5);
}
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ;
++ioBuf.ptr;
}
return;
}else if (!(kPS_Creator & dscFlags) &&
CheckFileSpace ( fileRef, &ioBuf, kPSContainsForString.length() )&&
CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsForString.c_str()), kPSContainsForString.length() ))
{
ioBuf.ptr+=kPSContainsForString.length();
if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscFor) ) return ;
}
else if (!(kPS_CreatorTool & dscFlags) &&
CheckFileSpace ( fileRef, &ioBuf, kPSContainsCreatorString.length() )&&
CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsCreatorString.c_str()), kPSContainsCreatorString.length() ))
{
ioBuf.ptr+=kPSContainsCreatorString.length();
if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscCreator) ) return ;
}
else if (!(kPS_CreateDate & dscFlags) &&
CheckFileSpace ( fileRef, &ioBuf, kPSContainsCreateDateString.length() )&&
CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsCreateDateString.c_str()), kPSContainsCreateDateString.length() ))
{
ioBuf.ptr+=kPSContainsCreateDateString.length();
if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscCreateDate) ) return ;
}
else if (!(kPS_Title & dscFlags) &&
CheckFileSpace ( fileRef, &ioBuf, kPSContainsTitleString.length() )&&
CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsTitleString.c_str()), kPSContainsTitleString.length() ))
{
ioBuf.ptr+=kPSContainsTitleString.length();
if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscTitle) ) return ;
}
else if( CheckFileSpace ( fileRef, &ioBuf, kPSContainsXMPString.length() )&&
( CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsXMPString.c_str()), kPSContainsXMPString.length() ) )) {
XMP_Int64 containsXMPStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data;
ioBuf.ptr += kPSContainsXMPString.length();
ExtractContainsXMPHint(ioBuf,containsXMPStartpos);
} // Found "%ADO_ContainsXMP:".
if ( ! PostScript_Support::SkipUntilNewline(fileRef,ioBuf) ) return ;
} // Outer marker loop.
|
CWE-125
| 178,167 | 10,355 |
165184041517307401681740363709435218919
| null | null | null |
exempi
|
e163667a06a9b656a047b0ec660b871f29a83c9f
| 1 |
void TIFF_MetaHandler::ProcessXMP()
{
this->processedXMP = true; // Make sure we only come through here once.
bool found;
bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0);
if ( readOnly ) {
this->psirMgr = new PSIR_MemoryReader();
this->iptcMgr = new IPTC_Reader();
} else {
this->psirMgr = new PSIR_FileWriter();
this->iptcMgr = new IPTC_Writer(); // ! Parse it later.
}
TIFF_Manager & tiff = this->tiffMgr; // Give the compiler help in recognizing non-aliases.
PSIR_Manager & psir = *this->psirMgr;
IPTC_Manager & iptc = *this->iptcMgr;
TIFF_Manager::TagInfo psirInfo;
bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo );
if ( havePSIR ) { // ! Do the Photoshop 6 integration before other legacy analysis.
psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen );
PSIR_Manager::ImgRsrcInfo buriedExif;
found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif );
if ( found ) {
tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen );
if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif );
}
}
TIFF_Manager::TagInfo iptcInfo;
bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); // The TIFF IPTC tag.
int iptcDigestState = kDigestMatches;
if ( haveIPTC ) {
bool haveDigest = false;
PSIR_Manager::ImgRsrcInfo digestInfo;
if ( havePSIR ) haveDigest = psir.GetImgRsrc ( kPSIR_IPTCDigest, &digestInfo );
if ( digestInfo.dataLen != 16 ) haveDigest = false;
if ( ! haveDigest ) {
iptcDigestState = kDigestMissing;
} else {
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, iptcInfo.dataLen, digestInfo.dataPtr );
if ( (iptcDigestState == kDigestDiffers) && (kTIFF_TypeSizes[iptcInfo.type] > 1) ) {
XMP_Uns8 * endPtr = (XMP_Uns8*)iptcInfo.dataPtr + iptcInfo.dataLen - 1;
XMP_Uns8 * minPtr = endPtr - kTIFF_TypeSizes[iptcInfo.type] + 1;
while ( (endPtr >= minPtr) && (*endPtr == 0) ) --endPtr;
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, unpaddedLen, digestInfo.dataPtr );
}
}
}
XMP_OptionBits options = k2XMP_FileHadExif; // TIFF files are presumed to have Exif legacy.
if ( haveIPTC ) options |= k2XMP_FileHadIPTC;
if ( this->containsXMP ) options |= k2XMP_FileHadXMP;
bool haveXMP = false;
if ( ! this->xmpPacket.empty() ) {
XMP_Assert ( this->containsXMP );
XMP_StringPtr packetStr = this->xmpPacket.c_str();
XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size();
try {
this->xmpObj.ParseFromBuffer ( packetStr, packetLen );
} catch ( ... ) { /* Ignore parsing failures, someday we hope to get partial XMP back. */ }
haveXMP = true;
}
if ( haveIPTC && (! haveXMP) && (iptcDigestState == kDigestMatches) ) iptcDigestState = kDigestMissing;
bool parseIPTC = (iptcDigestState != kDigestMatches) || (! readOnly);
if ( parseIPTC ) iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen );
ImportPhotoData ( tiff, iptc, psir, iptcDigestState, &this->xmpObj, options );
this->containsXMP = true; // Assume we now have something in the XMP.
} // TIFF_MetaHandler::ProcessXMP
|
CWE-125
| 178,168 | 10,356 |
278385762276260139331855759675956504309
| null | null | null |
qemu
|
ff589551c8e8e9e95e211b9d8daafb4ed39f1aec
| 1 |
uint64_t esp_reg_read(ESPState *s, uint32_t saddr)
{
uint32_t old_val;
trace_esp_mem_readb(saddr, s->rregs[saddr]);
switch (saddr) {
case ESP_FIFO:
if (s->ti_size > 0) {
s->ti_size--;
if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) {
/* Data out. */
qemu_log_mask(LOG_UNIMP,
"esp: PIO data read not implemented\n");
s->rregs[ESP_FIFO] = 0;
} else {
s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++];
}
esp_raise_irq(s);
}
if (s->ti_size == 0) {
s->ti_rptr = 0;
s->ti_wptr = 0;
}
s->ti_wptr = 0;
}
break;
case ESP_RINTR:
/* Clear sequence step, interrupt register and all status bits
except TC */
old_val = s->rregs[ESP_RINTR];
s->rregs[ESP_RINTR] = 0;
s->rregs[ESP_RSTAT] &= ~STAT_TC;
s->rregs[ESP_RSEQ] = SEQ_CD;
esp_lower_irq(s);
return old_val;
case ESP_TCHI:
/* Return the unique id if the value has never been written */
if (!s->tchi_written) {
return s->chip_id;
}
default:
break;
}
|
CWE-20
| 178,184 | 10,357 |
72724588902044741697465770787288603485
| null | null | null |
qemu
|
06630554ccbdd25780aa03c3548aaff1eb56dffd
| 1 |
static void mptsas_fetch_request(MPTSASState *s)
{
PCIDevice *pci = (PCIDevice *) s;
char req[MPTSAS_MAX_REQUEST_SIZE];
MPIRequestHeader *hdr = (MPIRequestHeader *)req;
hwaddr addr;
int size;
if (s->state != MPI_IOC_STATE_OPERATIONAL) {
mptsas_set_fault(s, MPI_IOCSTATUS_INVALID_STATE);
return;
}
/* Read the message header from the guest first. */
addr = s->host_mfa_high_addr | MPTSAS_FIFO_GET(s, request_post);
pci_dma_read(pci, addr, req, sizeof(hdr));
}
|
CWE-20
| 178,189 | 10,358 |
96357672494176480720335058690276855261
| null | null | null |
qemu
|
fa365d7cd11185237471823a5a33d36765454e16
| 1 |
static uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size)
{
AcpiPciHpState *s = opaque;
uint32_t val = 0;
int bsel = s->hotplug_select;
if (bsel < 0 || bsel > ACPI_PCIHP_MAX_HOTPLUG_BUS) {
return 0;
}
switch (addr) {
case PCI_UP_BASE:
val = s->acpi_pcihp_pci_status[bsel].up;
if (!s->legacy_piix) {
s->acpi_pcihp_pci_status[bsel].up = 0;
}
ACPI_PCIHP_DPRINTF("pci_up_read %" PRIu32 "\n", val);
break;
case PCI_DOWN_BASE:
val = s->acpi_pcihp_pci_status[bsel].down;
ACPI_PCIHP_DPRINTF("pci_down_read %" PRIu32 "\n", val);
break;
case PCI_EJ_BASE:
/* No feature defined yet */
ACPI_PCIHP_DPRINTF("pci_features_read %" PRIu32 "\n", val);
break;
case PCI_RMV_BASE:
val = s->acpi_pcihp_pci_status[bsel].hotplug_enable;
ACPI_PCIHP_DPRINTF("pci_rmv_read %" PRIu32 "\n", val);
break;
case PCI_SEL_BASE:
val = s->hotplug_select;
ACPI_PCIHP_DPRINTF("pci_sel_read %" PRIu32 "\n", val);
default:
break;
}
return val;
}
|
CWE-119
| 178,191 | 10,360 |
315249599671935633156203457129596917263
| null | null | null |
postgresql
|
932ded2ed51e8333852e370c7a6dad75d9f236f9
| 1 |
px_crypt_des(const char *key, const char *setting)
{
int i;
uint32 count,
salt,
l,
r0,
r1,
keybuf[2];
char *p;
uint8 *q;
static char output[21];
if (!des_initialised)
des_init();
/*
* Copy the key, shifting each character up by one bit and padding with
* zeros.
*/
q = (uint8 *) keybuf;
while (q - (uint8 *) keybuf - 8)
{
if ((*q++ = *key << 1))
key++;
}
if (des_setkey((char *) keybuf))
#ifndef DISABLE_XDES
if (*setting == _PASSWORD_EFMT1)
{
/*
* "new"-style: setting - underscore, 4 bytes of count, 4 bytes of
* salt key - unlimited characters
*/
for (i = 1, count = 0L; i < 5; i++)
count |= ascii_to_bin(setting[i]) << (i - 1) * 6;
for (i = 5, salt = 0L; i < 9; i++)
salt |= ascii_to_bin(setting[i]) << (i - 5) * 6;
while (*key)
{
/*
* Encrypt the key with itself.
*/
if (des_cipher((char *) keybuf, (char *) keybuf, 0L, 1))
return (NULL);
/*
* And XOR with the next 8 characters of the key.
*/
q = (uint8 *) keybuf;
while (q - (uint8 *) keybuf - 8 && *key)
*q++ ^= *key++ << 1;
if (des_setkey((char *) keybuf))
return (NULL);
}
strncpy(output, setting, 9);
/*
* Double check that we weren't given a short setting. If we were, the
* above code will probably have created weird values for count and
* salt, but we don't really care. Just make sure the output string
* doesn't have an extra NUL in it.
*/
output[9] = '\0';
p = output + strlen(output);
}
else
#endif /* !DISABLE_XDES */
{
/*
* "old"-style: setting - 2 bytes of salt key - up to 8 characters
*/
count = 25;
salt = (ascii_to_bin(setting[1]) << 6)
| ascii_to_bin(setting[0]);
output[0] = setting[0];
/*
* If the encrypted password that the salt was extracted from is only
* 1 character long, the salt will be corrupted. We need to ensure
* that the output string doesn't have an extra NUL in it!
*/
output[1] = setting[1] ? setting[1] : output[0];
p = output + 2;
}
setup_salt(salt);
/*
* Do it.
*/
if (do_des(0L, 0L, &r0, &r1, count))
return (NULL);
/*
* Now encode the result...
*/
l = (r0 >> 8);
*p++ = _crypt_a64[(l >> 18) & 0x3f];
*p++ = _crypt_a64[(l >> 12) & 0x3f];
*p++ = _crypt_a64[(l >> 6) & 0x3f];
*p++ = _crypt_a64[l & 0x3f];
l = (r0 << 16) | ((r1 >> 16) & 0xffff);
*p++ = _crypt_a64[(l >> 18) & 0x3f];
*p++ = _crypt_a64[(l >> 12) & 0x3f];
*p++ = _crypt_a64[(l >> 6) & 0x3f];
*p++ = _crypt_a64[l & 0x3f];
l = r1 << 2;
*p++ = _crypt_a64[(l >> 12) & 0x3f];
*p++ = _crypt_a64[(l >> 6) & 0x3f];
*p++ = _crypt_a64[l & 0x3f];
*p = 0;
return (output);
}
|
CWE-310
| 178,199 | 10,361 |
83043489652445959210413005542903472141
| null | null | null |
php
|
aab49e934de1fff046e659cbec46e3d053b41c34
| 1 |
_crypt_extended_r(const char *key, const char *setting,
struct php_crypt_extended_data *data)
{
int i;
uint32_t count, salt, l, r0, r1, keybuf[2];
u_char *p, *q;
if (!data->initialized)
des_init_local(data);
/*
* Copy the key, shifting each character up by one bit
* and padding with zeros.
*/
q = (u_char *) keybuf;
while (q - (u_char *) keybuf < sizeof(keybuf)) {
if ((*q++ = *key << 1))
key++;
}
if (des_setkey((u_char *) keybuf, data))
if (*setting == _PASSWORD_EFMT1) {
/*
* "new"-style:
* setting - underscore, 4 chars of count, 4 chars of salt
* key - unlimited characters
*/
for (i = 1, count = 0; i < 5; i++) {
int value = ascii_to_bin(setting[i]);
if (ascii64[value] != setting[i])
return(NULL);
count |= value << (i - 1) * 6;
}
if (!count)
return(NULL);
for (i = 5, salt = 0; i < 9; i++) {
int value = ascii_to_bin(setting[i]);
if (ascii64[value] != setting[i])
return(NULL);
salt |= value << (i - 5) * 6;
}
while (*key) {
/*
* Encrypt the key with itself.
*/
if (des_cipher((u_char *) keybuf, (u_char *) keybuf,
0, 1, data))
return(NULL);
/*
* And XOR with the next 8 characters of the key.
*/
q = (u_char *) keybuf;
while (q - (u_char *) keybuf < sizeof(keybuf) && *key)
*q++ ^= *key++ << 1;
if (des_setkey((u_char *) keybuf, data))
return(NULL);
}
memcpy(data->output, setting, 9);
data->output[9] = '\0';
p = (u_char *) data->output + 9;
} else {
/*
* "old"-style:
* setting - 2 chars of salt
* key - up to 8 characters
*/
count = 25;
if (ascii_is_unsafe(setting[0]) || ascii_is_unsafe(setting[1]))
return(NULL);
salt = (ascii_to_bin(setting[1]) << 6)
| ascii_to_bin(setting[0]);
data->output[0] = setting[0];
data->output[1] = setting[1];
p = (u_char *) data->output + 2;
}
setup_salt(salt, data);
/*
* Do it.
*/
if (do_des(0, 0, &r0, &r1, count, data))
return(NULL);
/*
* Now encode the result...
*/
l = (r0 >> 8);
*p++ = ascii64[(l >> 18) & 0x3f];
*p++ = ascii64[(l >> 12) & 0x3f];
*p++ = ascii64[(l >> 6) & 0x3f];
*p++ = ascii64[l & 0x3f];
l = (r0 << 16) | ((r1 >> 16) & 0xffff);
*p++ = ascii64[(l >> 18) & 0x3f];
*p++ = ascii64[(l >> 12) & 0x3f];
*p++ = ascii64[(l >> 6) & 0x3f];
*p++ = ascii64[l & 0x3f];
l = r1 << 2;
*p++ = ascii64[(l >> 12) & 0x3f];
*p++ = ascii64[(l >> 6) & 0x3f];
*p++ = ascii64[l & 0x3f];
*p = 0;
return(data->output);
}
|
CWE-310
| 178,200 | 10,362 |
325649762106707106315525655465892010339
| null | null | null |
php
|
082aecfc3a753ad03be82cf14f03ac065723ec92
| 1 |
static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC)
{
size_t length;
int tag, format, components;
char *value_ptr, tagname[64], cbuf[32], *outside=NULL;
size_t byte_count, offset_val, fpos, fgot;
int64_t byte_count_signed;
xp_field_type *tmp_xp;
#ifdef EXIF_DEBUG
char *dump_data;
int dump_free;
#endif /* EXIF_DEBUG */
/* Protect against corrupt headers */
if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached");
return FALSE;
}
ImageInfo->ifd_nesting_level++;
tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel);
format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);
if (!format || format > NUM_FORMATS) {
/* (-1) catches illegal zero case as unsigned underflows to positive large. */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format);
format = TAG_FMT_BYTE;
/*return TRUE;*/
}
if (components < 0) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components);
return FALSE;
}
byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format];
if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC));
return FALSE;
}
byte_count = (size_t)byte_count_signed;
if (byte_count > 4) {
offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
/* If its bigger than 4 bytes, the dir entry contains an offset. */
value_ptr = offset_base+offset_val;
/*
dir_entry is ImageInfo->file.list[sn].data+2+i*12
offset_base is ImageInfo->file.list[sn].data-dir_offset
dir_entry - offset_base is dir_offset+2+i*12
*/
if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) {
/* It is important to check for IMAGE_FILETYPE_TIFF
* JPEG does not use absolute pointers instead its pointers are
* relative to the start of the TIFF header in APP1 section. */
if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) {
if (value_ptr < dir_entry) {
/* we can read this if offset_val > 0 */
/* some files have their values in other parts of the file */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry);
} else {
/* this is for sure not allowed */
/* exception are IFD pointers */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength);
}
return FALSE;
}
if (byte_count>sizeof(cbuf)) {
/* mark as outside range and get buffer */
value_ptr = safe_emalloc(byte_count, 1, 0);
outside = value_ptr;
} else {
/* In most cases we only access a small range so
* it is faster to use a static buffer there
* BUT it offers also the possibility to have
* pointers read without the need to free them
* explicitley before returning. */
memset(&cbuf, 0, sizeof(cbuf));
value_ptr = cbuf;
}
fpos = php_stream_tell(ImageInfo->infile);
php_stream_seek(ImageInfo->infile, offset_val, SEEK_SET);
fgot = php_stream_tell(ImageInfo->infile);
if (fgot!=offset_val) {
EFREE_IF(outside);
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, offset_val);
return FALSE;
}
fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count);
php_stream_seek(ImageInfo->infile, fpos, SEEK_SET);
if (fgot<byte_count) {
EFREE_IF(outside);
EXIF_ERRLOG_FILEEOF(ImageInfo)
return FALSE;
}
}
} else {
/* 4 bytes or less and value is in the dir entry itself */
value_ptr = dir_entry+8;
offset_val= value_ptr-offset_base;
}
ImageInfo->sections_found |= FOUND_ANY_TAG;
#ifdef EXIF_DEBUG
dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC);
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data);
if (dump_free) {
efree(dump_data);
}
#endif
if (section_index==SECTION_THUMBNAIL) {
if (!ImageInfo->Thumbnail.data) {
switch(tag) {
case TAG_IMAGEWIDTH:
case TAG_COMP_IMAGE_WIDTH:
ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_IMAGEHEIGHT:
case TAG_COMP_IMAGE_HEIGHT:
ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_STRIP_OFFSETS:
case TAG_JPEG_INTERCHANGE_FORMAT:
/* accept both formats */
ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_STRIP_BYTE_COUNTS:
if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) {
ImageInfo->Thumbnail.filetype = ImageInfo->FileType;
} else {
/* motorola is easier to read */
ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM;
}
ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_JPEG_INTERCHANGE_FORMAT_LEN:
if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) {
ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG;
ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
}
break;
}
}
} else {
if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF)
switch(tag) {
case TAG_COPYRIGHT:
/* check for "<photographer> NUL <editor> NUL" */
if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) {
if (length<byte_count-1) {
/* When there are any characters after the first NUL */
ImageInfo->CopyrightPhotographer = estrdup(value_ptr);
ImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1);
spprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, value_ptr+length+1);
/* format = TAG_FMT_UNDEFINED; this musn't be ASCII */
/* but we are not supposed to change this */
/* keep in mind that image_info does not store editor value */
} else {
ImageInfo->Copyright = estrndup(value_ptr, byte_count);
}
}
break;
case TAG_USERCOMMENT:
ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC);
break;
case TAG_XP_TITLE:
case TAG_XP_COMMENTS:
case TAG_XP_AUTHOR:
case TAG_XP_KEYWORDS:
case TAG_XP_SUBJECT:
tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0);
ImageInfo->sections_found |= FOUND_WINXP;
ImageInfo->xp_fields.list = tmp_xp;
ImageInfo->xp_fields.count++;
exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC);
break;
case TAG_FNUMBER:
/* Simplest way of expressing aperture, so I trust it the most.
(overwrite previously computed value if there is one) */
ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_APERTURE:
case TAG_MAX_APERTURE:
/* More relevant info always comes earlier, so only use this field if we don't
have appropriate aperture information yet. */
if (ImageInfo->ApertureFNumber == 0) {
ImageInfo->ApertureFNumber
= (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5);
}
break;
case TAG_SHUTTERSPEED:
/* More complicated way of expressing exposure time, so only use
this value if we don't already have it from somewhere else.
SHUTTERSPEED comes after EXPOSURE TIME
*/
if (ImageInfo->ExposureTime == 0) {
ImageInfo->ExposureTime
= (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)));
}
break;
case TAG_EXPOSURETIME:
ImageInfo->ExposureTime = -1;
break;
case TAG_COMP_IMAGE_WIDTH:
ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_FOCALPLANE_X_RES:
ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_SUBJECT_DISTANCE:
/* Inidcates the distacne the autofocus camera is focused to.
Tends to be less accurate as distance increases. */
ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_FOCALPLANE_RESOLUTION_UNIT:
switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) {
case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */
case 2:
/* According to the information I was using, 2 measn meters.
But looking at the Cannon powershot's files, inches is the only
sensible value. */
ImageInfo->FocalplaneUnits = 25.4;
break;
case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */
case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */
case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */
}
break;
case TAG_SUB_IFD:
if (format==TAG_FMT_IFD) {
/* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */
/* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */
/* JPEG do we have the data area and what to do with it */
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD");
}
break;
case TAG_MAKE:
ImageInfo->make = estrndup(value_ptr, byte_count);
break;
case TAG_MODEL:
ImageInfo->model = estrndup(value_ptr, byte_count);
break;
case TAG_MAKER_NOTE:
exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC);
break;
case TAG_EXIF_IFD_POINTER:
case TAG_GPS_IFD_POINTER:
case TAG_INTEROP_IFD_POINTER:
if (ReadNextIFD) {
char *Subdir_start;
int sub_section_index = 0;
switch(tag) {
case TAG_EXIF_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF");
#endif
ImageInfo->sections_found |= FOUND_EXIF;
sub_section_index = SECTION_EXIF;
break;
case TAG_GPS_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS");
#endif
ImageInfo->sections_found |= FOUND_GPS;
sub_section_index = SECTION_GPS;
break;
case TAG_INTEROP_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY");
#endif
ImageInfo->sections_found |= FOUND_INTEROP;
sub_section_index = SECTION_INTEROP;
break;
}
Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel);
if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer");
return FALSE;
}
if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) {
return FALSE;
}
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index));
#endif
}
}
}
exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC);
EFREE_IF(outside);
return TRUE;
}
|
CWE-119
| 178,204 | 10,364 |
70536523963492635216375732764446791597
| null | null | null |
php
|
fd9689745c44341b1bd6af4756f324be8abba2fb
| 1 |
PHP_FUNCTION(grapheme_strpos)
{
unsigned char *haystack, *needle;
int haystack_len, needle_len;
unsigned char *found;
long loffset = 0;
int32_t offset = 0;
int ret_pos;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", (char **)&haystack, &haystack_len, (char **)&needle, &needle_len, &loffset) == FAILURE) {
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"grapheme_strpos: unable to parse input param", 0 TSRMLS_CC );
RETURN_FALSE;
}
if ( OUTSIDE_STRING(loffset, haystack_len) ) {
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Offset not contained in string", 1 TSRMLS_CC );
RETURN_FALSE;
}
/* we checked that it will fit: */
offset = (int32_t) loffset;
/* the offset is 'grapheme count offset' so it still might be invalid - we'll check it later */
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Empty delimiter", 1 TSRMLS_CC );
RETURN_FALSE;
}
| 178,206 | 10,366 |
318580545897039969714028472837162988843
| null | null | null |
|
php
|
dccda88f27a084bcbbb30198ace12b4e7ae961cc
| 1 |
void _xml_characterDataHandler(void *userData, const XML_Char *s, int len)
{
xml_parser *parser = (xml_parser *)userData;
if (parser) {
zval *retval, *args[2];
if (parser->characterDataHandler) {
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_xmlchar_zval(s, len, parser->target_encoding);
if ((retval = xml_call_handler(parser, parser->characterDataHandler, parser->characterDataPtr, 2, args))) {
zval_ptr_dtor(&retval);
}
}
if (parser->data) {
int i;
int doprint = 0;
char *decoded_value;
int decoded_len;
decoded_value = xml_utf8_decode(s,len,&decoded_len,parser->target_encoding);
for (i = 0; i < decoded_len; i++) {
switch (decoded_value[i]) {
case ' ':
case '\t':
case '\n':
continue;
default:
doprint = 1;
break;
}
if (doprint) {
break;
}
}
if (doprint || (! parser->skipwhite)) {
if (parser->lastwasopen) {
zval **myval;
/* check if the current tag already has a value - if yes append to that! */
if (zend_hash_find(Z_ARRVAL_PP(parser->ctag),"value",sizeof("value"),(void **) &myval) == SUCCESS) {
int newlen = Z_STRLEN_PP(myval) + decoded_len;
Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1);
strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1);
Z_STRLEN_PP(myval) += decoded_len;
efree(decoded_value);
} else {
add_assoc_string(*(parser->ctag),"value",decoded_value,0);
}
} else {
zval *tag;
zval **curtag, **mytype, **myval;
HashPosition hpos=NULL;
zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(parser->data), &hpos);
if (hpos && (zend_hash_get_current_data_ex(Z_ARRVAL_P(parser->data), (void **) &curtag, &hpos) == SUCCESS)) {
if (zend_hash_find(Z_ARRVAL_PP(curtag),"type",sizeof("type"),(void **) &mytype) == SUCCESS) {
if (!strcmp(Z_STRVAL_PP(mytype), "cdata")) {
if (zend_hash_find(Z_ARRVAL_PP(curtag),"value",sizeof("value"),(void **) &myval) == SUCCESS) {
int newlen = Z_STRLEN_PP(myval) + decoded_len;
Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1);
strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1);
Z_STRLEN_PP(myval) += decoded_len;
efree(decoded_value);
return;
}
}
}
}
if (parser->level <= XML_MAXLEVEL) {
MAKE_STD_ZVAL(tag);
array_init(tag);
_xml_add_to_info(parser,parser->ltags[parser->level-1] + parser->toffset);
add_assoc_string(tag,"tag",parser->ltags[parser->level-1] + parser->toffset,1);
add_assoc_string(tag,"value",decoded_value,0);
add_assoc_string(tag,"type","cdata",1);
add_assoc_long(tag,"level",parser->level);
zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL);
} else if (parser->level == (XML_MAXLEVEL + 1)) {
TSRMLS_FETCH();
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated");
}
}
} else {
efree(decoded_value);
}
}
}
}
|
CWE-119
| 178,212 | 10,372 |
224440066981949645025854947509044070929
| null | null | null |
php
|
6e25966544fb1d2f3d7596e060ce9c9269bbdcf8
| 1 |
static void php_snmp_error(zval *object, const char *docref, int type, const char *format, ...)
{
va_list args;
php_snmp_object *snmp_object = NULL;
if (object) {
snmp_object = Z_SNMP_P(object);
if (type == PHP_SNMP_ERRNO_NOERROR) {
memset(snmp_object->snmp_errstr, 0, sizeof(snmp_object->snmp_errstr));
} else {
va_start(args, format);
vsnprintf(snmp_object->snmp_errstr, sizeof(snmp_object->snmp_errstr) - 1, format, args);
va_end(args);
}
snmp_object->snmp_errno = type;
}
if (type == PHP_SNMP_ERRNO_NOERROR) {
return;
}
if (object && (snmp_object->exceptions_enabled & type)) {
zend_throw_exception_ex(php_snmp_exception_ce, type, snmp_object->snmp_errstr);
} else {
va_start(args, format);
php_verror(docref, "", E_WARNING, format, args);
va_end(args);
}
}
|
CWE-20
| 178,246 | 10,398 |
329927345140767595269248207323259191320
| null | null | null |
qemu
|
1ae3f2f178087711f9591350abad133525ba93f2
| 1 |
static void ehci_advance_state(EHCIState *ehci, int async)
{
EHCIQueue *q = NULL;
int again;
do {
case EST_WAITLISTHEAD:
again = ehci_state_waitlisthead(ehci, async);
break;
case EST_FETCHENTRY:
again = ehci_state_fetchentry(ehci, async);
break;
case EST_FETCHQH:
q = ehci_state_fetchqh(ehci, async);
if (q != NULL) {
assert(q->async == async);
again = 1;
} else {
again = 0;
}
break;
case EST_FETCHITD:
again = ehci_state_fetchitd(ehci, async);
break;
case EST_FETCHSITD:
again = ehci_state_fetchsitd(ehci, async);
break;
case EST_ADVANCEQUEUE:
case EST_FETCHQTD:
assert(q != NULL);
again = ehci_state_fetchqtd(q);
break;
case EST_HORIZONTALQH:
assert(q != NULL);
again = ehci_state_horizqh(q);
break;
case EST_EXECUTE:
assert(q != NULL);
again = ehci_state_execute(q);
if (async) {
ehci->async_stepdown = 0;
}
break;
case EST_EXECUTING:
assert(q != NULL);
if (async) {
ehci->async_stepdown = 0;
}
again = ehci_state_executing(q);
break;
case EST_WRITEBACK:
assert(q != NULL);
again = ehci_state_writeback(q);
if (!async) {
ehci->periodic_sched_active = PERIODIC_ACTIVE;
}
break;
default:
fprintf(stderr, "Bad state!\n");
again = -1;
g_assert_not_reached();
break;
}
break;
}
|
CWE-20
| 178,247 | 10,399 |
389763387610975553416490626197170726
| null | null | null |
qemu
|
691a02e2ce0c413236a78dee6f2651c937b09fb0
| 1 |
static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip)
{
CPUState *cs = CPU(cpu);
CPUX86State *env = &cpu->env;
VAPICHandlers *handlers;
uint8_t opcode[2];
uint32_t imm32;
target_ulong current_pc = 0;
target_ulong current_cs_base = 0;
uint32_t current_flags = 0;
if (smp_cpus == 1) {
handlers = &s->rom_state.up;
} else {
handlers = &s->rom_state.mp;
}
if (!kvm_enabled()) {
cpu_get_tb_cpu_state(env, ¤t_pc, ¤t_cs_base,
¤t_flags);
}
pause_all_vcpus();
cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0);
switch (opcode[0]) {
case 0x89: /* mov r32 to r/m32 */
patch_byte(cpu, ip, 0x50 + modrm_reg(opcode[1])); /* push reg */
patch_call(s, cpu, ip + 1, handlers->set_tpr);
break;
case 0x8b: /* mov r/m32 to r32 */
patch_byte(cpu, ip, 0x90);
patch_call(s, cpu, ip + 1, handlers->get_tpr[modrm_reg(opcode[1])]);
break;
case 0xa1: /* mov abs to eax */
patch_call(s, cpu, ip, handlers->get_tpr[0]);
break;
case 0xa3: /* mov eax to abs */
patch_call(s, cpu, ip, handlers->set_tpr_eax);
break;
case 0xc7: /* mov imm32, r/m32 (c7/0) */
patch_byte(cpu, ip, 0x68); /* push imm32 */
cpu_memory_rw_debug(cs, ip + 6, (void *)&imm32, sizeof(imm32), 0);
cpu_memory_rw_debug(cs, ip + 1, (void *)&imm32, sizeof(imm32), 1);
patch_call(s, cpu, ip + 5, handlers->set_tpr);
break;
case 0xff: /* push r/m32 */
patch_byte(cpu, ip, 0x50); /* push eax */
patch_call(s, cpu, ip + 1, handlers->get_tpr_stack);
break;
default:
abort();
}
resume_all_vcpus();
if (!kvm_enabled()) {
tb_gen_code(cs, current_pc, current_cs_base, current_flags, 1);
cpu_resume_from_signal(cs, NULL);
}
}
|
CWE-200
| 178,248 | 10,400 |
319434310877393653202091774663036335170
| null | null | null |
php
|
56754a7f9eba0e4f559b6ca081d9f2a447b3f159
| 1 |
static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
long datalen;
datalen = parse_iv2((*p) + 2, p);
(*p) += 2;
if (datalen < 0 || (*p) + datalen >= max) {
zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p)));
return 0;
}
if (ce->unserialize == NULL) {
zend_error(E_WARNING, "Class %s has no unserializer", ce->name);
object_init_ex(*rval, ce);
} else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) {
return 0;
}
(*p) += datalen;
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
|
CWE-189
| 178,321 | 10,401 |
243590710243142569022388540940865883003
| null | null | null |
php
|
eaf4e77190d402ea014207e9a7d5da1a4f3727ba
| 1 |
int make_http_soap_request(zval *this_ptr,
zend_string *buf,
char *location,
char *soapaction,
int soap_version,
zval *return_value)
{
zend_string *request;
smart_str soap_headers = {0};
smart_str soap_headers_z = {0};
int err;
php_url *phpurl = NULL;
php_stream *stream;
zval *trace, *tmp;
int use_proxy = 0;
int use_ssl;
zend_string *http_body;
char *content_type, *http_version, *cookie_itt;
int http_close;
zend_string *http_headers;
char *connection;
int http_1_1;
int http_status;
int content_type_xml = 0;
zend_long redirect_max = 20;
char *content_encoding;
char *http_msg = NULL;
zend_bool old_allow_url_fopen;
php_stream_context *context = NULL;
zend_bool has_authorization = 0;
zend_bool has_proxy_authorization = 0;
zend_bool has_cookies = 0;
if (this_ptr == NULL || Z_TYPE_P(this_ptr) != IS_OBJECT) {
return FALSE;
}
request = buf;
/* Compress request */
if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "compression", sizeof("compression")-1)) != NULL && Z_TYPE_P(tmp) == IS_LONG) {
int level = Z_LVAL_P(tmp) & 0x0f;
int kind = Z_LVAL_P(tmp) & SOAP_COMPRESSION_DEFLATE;
if (level > 9) {level = 9;}
if ((Z_LVAL_P(tmp) & SOAP_COMPRESSION_ACCEPT) != 0) {
smart_str_append_const(&soap_headers_z,"Accept-Encoding: gzip, deflate\r\n");
}
if (level > 0) {
zval func;
zval retval;
zval params[3];
int n;
ZVAL_STR_COPY(¶ms[0], buf);
ZVAL_LONG(¶ms[1], level);
if (kind == SOAP_COMPRESSION_DEFLATE) {
n = 2;
ZVAL_STRING(&func, "gzcompress");
smart_str_append_const(&soap_headers_z,"Content-Encoding: deflate\r\n");
} else {
n = 3;
ZVAL_STRING(&func, "gzencode");
smart_str_append_const(&soap_headers_z,"Content-Encoding: gzip\r\n");
ZVAL_LONG(¶ms[2], 0x1f);
}
if (call_user_function(CG(function_table), (zval*)NULL, &func, &retval, n, params) == SUCCESS &&
Z_TYPE(retval) == IS_STRING) {
zval_ptr_dtor(¶ms[0]);
zval_ptr_dtor(&func);
request = Z_STR(retval);
} else {
zval_ptr_dtor(¶ms[0]);
zval_ptr_dtor(&func);
if (request != buf) {
zend_string_release(request);
}
smart_str_free(&soap_headers_z);
return FALSE;
}
}
}
if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1)) != NULL) {
php_stream_from_zval_no_verify(stream,tmp);
if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1)) != NULL && Z_TYPE_P(tmp) == IS_LONG) {
use_proxy = Z_LVAL_P(tmp);
}
} else {
stream = NULL;
}
if (location != NULL && location[0] != '\000') {
phpurl = php_url_parse(location);
}
if (NULL != (tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr),
"_stream_context", sizeof("_stream_context")-1))) {
context = php_stream_context_from_zval(tmp, 0);
}
if (context &&
(tmp = php_stream_context_get_option(context, "http", "max_redirects")) != NULL) {
if (Z_TYPE_P(tmp) != IS_STRING || !is_numeric_string(Z_STRVAL_P(tmp), Z_STRLEN_P(tmp), &redirect_max, NULL, 1)) {
if (Z_TYPE_P(tmp) == IS_LONG)
redirect_max = Z_LVAL_P(tmp);
}
}
try_again:
if (phpurl == NULL || phpurl->host == NULL) {
if (phpurl != NULL) {php_url_free(phpurl);}
if (request != buf) {
zend_string_release(request);
}
add_soap_fault(this_ptr, "HTTP", "Unable to parse URL", NULL, NULL);
smart_str_free(&soap_headers_z);
return FALSE;
}
use_ssl = 0;
if (phpurl->scheme != NULL && strcmp(phpurl->scheme, "https") == 0) {
use_ssl = 1;
} else if (phpurl->scheme == NULL || strcmp(phpurl->scheme, "http") != 0) {
php_url_free(phpurl);
if (request != buf) {
zend_string_release(request);
}
add_soap_fault(this_ptr, "HTTP", "Unknown protocol. Only http and https are allowed.", NULL, NULL);
smart_str_free(&soap_headers_z);
return FALSE;
}
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
if (use_ssl && php_stream_locate_url_wrapper("https://", NULL, STREAM_LOCATE_WRAPPERS_ONLY) == NULL) {
php_url_free(phpurl);
if (request != buf) {
zend_string_release(request);
}
add_soap_fault(this_ptr, "HTTP", "SSL support is not available in this build", NULL, NULL);
PG(allow_url_fopen) = old_allow_url_fopen;
smart_str_free(&soap_headers_z);
return FALSE;
}
if (phpurl->port == 0) {
phpurl->port = use_ssl ? 443 : 80;
}
/* Check if request to the same host */
if (stream != NULL) {
php_url *orig;
if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1)) != NULL &&
(orig = (php_url *) zend_fetch_resource_ex(tmp, "httpurl", le_url)) != NULL &&
((use_proxy && !use_ssl) ||
(((use_ssl && orig->scheme != NULL && strcmp(orig->scheme, "https") == 0) ||
(!use_ssl && orig->scheme == NULL) ||
(!use_ssl && strcmp(orig->scheme, "https") != 0)) &&
strcmp(orig->host, phpurl->host) == 0 &&
orig->port == phpurl->port))) {
} else {
php_stream_close(stream);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
stream = NULL;
use_proxy = 0;
}
}
/* Check if keep-alive connection is still opened */
if (stream != NULL && php_stream_eof(stream)) {
php_stream_close(stream);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
stream = NULL;
use_proxy = 0;
}
if (!stream) {
stream = http_connect(this_ptr, phpurl, use_ssl, context, &use_proxy);
if (stream) {
php_stream_auto_cleanup(stream);
add_property_resource(this_ptr, "httpsocket", stream->res);
GC_REFCOUNT(stream->res)++;
add_property_long(this_ptr, "_use_proxy", use_proxy);
} else {
php_url_free(phpurl);
if (request != buf) {
zend_string_release(request);
}
add_soap_fault(this_ptr, "HTTP", "Could not connect to host", NULL, NULL);
PG(allow_url_fopen) = old_allow_url_fopen;
smart_str_free(&soap_headers_z);
return FALSE;
}
}
PG(allow_url_fopen) = old_allow_url_fopen;
if (stream) {
zval *cookies, *login, *password;
zend_resource *ret = zend_register_resource(phpurl, le_url);
add_property_resource(this_ptr, "httpurl", ret);
GC_REFCOUNT(ret)++;
/*zend_list_addref(ret);*/
if (context &&
(tmp = php_stream_context_get_option(context, "http", "protocol_version")) != NULL &&
Z_TYPE_P(tmp) == IS_DOUBLE &&
Z_DVAL_P(tmp) == 1.0) {
http_1_1 = 0;
} else {
http_1_1 = 1;
}
smart_str_append_const(&soap_headers, "POST ");
if (use_proxy && !use_ssl) {
smart_str_appends(&soap_headers, phpurl->scheme);
smart_str_append_const(&soap_headers, "://");
smart_str_appends(&soap_headers, phpurl->host);
smart_str_appendc(&soap_headers, ':');
smart_str_append_unsigned(&soap_headers, phpurl->port);
}
if (phpurl->path) {
smart_str_appends(&soap_headers, phpurl->path);
} else {
smart_str_appendc(&soap_headers, '/');
}
if (phpurl->query) {
smart_str_appendc(&soap_headers, '?');
smart_str_appends(&soap_headers, phpurl->query);
}
if (phpurl->fragment) {
smart_str_appendc(&soap_headers, '#');
smart_str_appends(&soap_headers, phpurl->fragment);
}
if (http_1_1) {
smart_str_append_const(&soap_headers, " HTTP/1.1\r\n");
} else {
smart_str_append_const(&soap_headers, " HTTP/1.0\r\n");
}
smart_str_append_const(&soap_headers, "Host: ");
smart_str_appends(&soap_headers, phpurl->host);
if (phpurl->port != (use_ssl?443:80)) {
smart_str_appendc(&soap_headers, ':');
smart_str_append_unsigned(&soap_headers, phpurl->port);
}
if (!http_1_1 ||
((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_keep_alive", sizeof("_keep_alive")-1)) != NULL &&
(Z_TYPE_P(tmp) == IS_FALSE || (Z_TYPE_P(tmp) == IS_LONG && Z_LVAL_P(tmp) == 0)))) {
smart_str_append_const(&soap_headers, "\r\n"
"Connection: close\r\n");
} else {
smart_str_append_const(&soap_headers, "\r\n"
"Connection: Keep-Alive\r\n");
}
if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_user_agent", sizeof("_user_agent")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
if (Z_STRLEN_P(tmp) > 0) {
smart_str_append_const(&soap_headers, "User-Agent: ");
smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
smart_str_append_const(&soap_headers, "\r\n");
}
} else if (context &&
(tmp = php_stream_context_get_option(context, "http", "user_agent")) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
if (Z_STRLEN_P(tmp) > 0) {
smart_str_append_const(&soap_headers, "User-Agent: ");
smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
smart_str_append_const(&soap_headers, "\r\n");
}
} else if (FG(user_agent)) {
smart_str_append_const(&soap_headers, "User-Agent: ");
smart_str_appends(&soap_headers, FG(user_agent));
smart_str_append_const(&soap_headers, "\r\n");
} else {
smart_str_append_const(&soap_headers, "User-Agent: PHP-SOAP/"PHP_VERSION"\r\n");
}
smart_str_append_smart_str(&soap_headers, &soap_headers_z);
if (soap_version == SOAP_1_2) {
smart_str_append_const(&soap_headers,"Content-Type: application/soap+xml; charset=utf-8");
if (soapaction) {
smart_str_append_const(&soap_headers,"; action=\"");
smart_str_appends(&soap_headers, soapaction);
smart_str_append_const(&soap_headers,"\"");
}
smart_str_append_const(&soap_headers,"\r\n");
} else {
smart_str_append_const(&soap_headers,"Content-Type: text/xml; charset=utf-8\r\n");
if (soapaction) {
smart_str_append_const(&soap_headers, "SOAPAction: \"");
smart_str_appends(&soap_headers, soapaction);
smart_str_append_const(&soap_headers, "\"\r\n");
}
}
smart_str_append_const(&soap_headers,"Content-Length: ");
smart_str_append_long(&soap_headers, request->len);
smart_str_append_const(&soap_headers, "\r\n");
/* HTTP Authentication */
if ((login = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login")-1)) != NULL &&
Z_TYPE_P(login) == IS_STRING) {
zval *digest;
has_authorization = 1;
if ((digest = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest")-1)) != NULL) {
if (Z_TYPE_P(digest) == IS_ARRAY) {
char HA1[33], HA2[33], response[33], cnonce[33], nc[9];
PHP_MD5_CTX md5ctx;
unsigned char hash[16];
PHP_MD5Init(&md5ctx);
snprintf(cnonce, sizeof(cnonce), ZEND_LONG_FMT, php_rand());
PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, strlen(cnonce));
PHP_MD5Final(hash, &md5ctx);
make_digest(cnonce, hash);
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nc", sizeof("nc")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_LONG) {
Z_LVAL_P(tmp)++;
snprintf(nc, sizeof(nc), "%08ld", Z_LVAL_P(tmp));
} else {
add_assoc_long(digest, "nc", 1);
strcpy(nc, "00000001");
}
PHP_MD5Init(&md5ctx);
PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(login), Z_STRLEN_P(login));
PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "realm", sizeof("realm")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
}
PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
if ((password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password")-1)) != NULL &&
Z_TYPE_P(password) == IS_STRING) {
PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(password), Z_STRLEN_P(password));
}
PHP_MD5Final(hash, &md5ctx);
make_digest(HA1, hash);
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "algorithm", sizeof("algorithm")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING &&
Z_STRLEN_P(tmp) == sizeof("md5-sess")-1 &&
stricmp(Z_STRVAL_P(tmp), "md5-sess") == 0) {
PHP_MD5Init(&md5ctx);
PHP_MD5Update(&md5ctx, (unsigned char*)HA1, 32);
PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nonce", sizeof("nonce")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
}
PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, 8);
PHP_MD5Final(hash, &md5ctx);
make_digest(HA1, hash);
}
PHP_MD5Init(&md5ctx);
PHP_MD5Update(&md5ctx, (unsigned char*)"POST:", sizeof("POST:")-1);
if (phpurl->path) {
PHP_MD5Update(&md5ctx, (unsigned char*)phpurl->path, strlen(phpurl->path));
} else {
PHP_MD5Update(&md5ctx, (unsigned char*)"/", 1);
}
if (phpurl->query) {
PHP_MD5Update(&md5ctx, (unsigned char*)"?", 1);
PHP_MD5Update(&md5ctx, (unsigned char*)phpurl->query, strlen(phpurl->query));
}
/* TODO: Support for qop="auth-int" */
/*
if (zend_hash_find(Z_ARRVAL_PP(digest), "qop", sizeof("qop"), (void **)&tmp) == SUCCESS &&
Z_TYPE_PP(tmp) == IS_STRING &&
Z_STRLEN_PP(tmp) == sizeof("auth-int")-1 &&
stricmp(Z_STRVAL_PP(tmp), "auth-int") == 0) {
PHP_MD5Update(&md5ctx, ":", 1);
PHP_MD5Update(&md5ctx, HEntity, HASHHEXLEN);
}
*/
PHP_MD5Final(hash, &md5ctx);
make_digest(HA2, hash);
PHP_MD5Init(&md5ctx);
PHP_MD5Update(&md5ctx, (unsigned char*)HA1, 32);
PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nonce", sizeof("nonce")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
}
PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "qop", sizeof("qop")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
PHP_MD5Update(&md5ctx, (unsigned char*)nc, 8);
PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, 8);
PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
/* TODO: Support for qop="auth-int" */
PHP_MD5Update(&md5ctx, (unsigned char*)"auth", sizeof("auth")-1);
PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
}
PHP_MD5Update(&md5ctx, (unsigned char*)HA2, 32);
PHP_MD5Final(hash, &md5ctx);
make_digest(response, hash);
smart_str_append_const(&soap_headers, "Authorization: Digest username=\"");
smart_str_appendl(&soap_headers, Z_STRVAL_P(login), Z_STRLEN_P(login));
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "realm", sizeof("realm")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
smart_str_append_const(&soap_headers, "\", realm=\"");
smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
}
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nonce", sizeof("nonce")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
smart_str_append_const(&soap_headers, "\", nonce=\"");
smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
}
smart_str_append_const(&soap_headers, "\", uri=\"");
if (phpurl->path) {
smart_str_appends(&soap_headers, phpurl->path);
} else {
smart_str_appendc(&soap_headers, '/');
}
if (phpurl->query) {
smart_str_appendc(&soap_headers, '?');
smart_str_appends(&soap_headers, phpurl->query);
}
if (phpurl->fragment) {
smart_str_appendc(&soap_headers, '#');
smart_str_appends(&soap_headers, phpurl->fragment);
}
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "qop", sizeof("qop")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
/* TODO: Support for qop="auth-int" */
smart_str_append_const(&soap_headers, "\", qop=\"auth");
smart_str_append_const(&soap_headers, "\", nc=\"");
smart_str_appendl(&soap_headers, nc, 8);
smart_str_append_const(&soap_headers, "\", cnonce=\"");
smart_str_appendl(&soap_headers, cnonce, 8);
}
smart_str_append_const(&soap_headers, "\", response=\"");
smart_str_appendl(&soap_headers, response, 32);
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "opaque", sizeof("opaque")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
smart_str_append_const(&soap_headers, "\", opaque=\"");
smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
}
if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "algorithm", sizeof("algorithm")-1)) != NULL &&
Z_TYPE_P(tmp) == IS_STRING) {
smart_str_append_const(&soap_headers, "\", algorithm=\"");
smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
}
smart_str_append_const(&soap_headers, "\"\r\n");
}
} else {
zend_string *buf;
smart_str auth = {0};
smart_str_appendl(&auth, Z_STRVAL_P(login), Z_STRLEN_P(login));
smart_str_appendc(&auth, ':');
if ((password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password")-1)) != NULL &&
Z_TYPE_P(password) == IS_STRING) {
smart_str_appendl(&auth, Z_STRVAL_P(password), Z_STRLEN_P(password));
}
smart_str_0(&auth);
buf = php_base64_encode((unsigned char*)ZSTR_VAL(auth.s), ZSTR_LEN(auth.s));
smart_str_append_const(&soap_headers, "Authorization: Basic ");
smart_str_appendl(&soap_headers, (char*)ZSTR_VAL(buf), ZSTR_LEN(buf));
smart_str_append_const(&soap_headers, "\r\n");
zend_string_release(buf);
smart_str_free(&auth);
}
}
/* Proxy HTTP Authentication */
if (use_proxy && !use_ssl) {
has_proxy_authorization = proxy_authentication(this_ptr, &soap_headers);
}
/* Send cookies along with request */
if ((cookies = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_cookies", sizeof("_cookies")-1)) != NULL &&
Z_TYPE_P(cookies) == IS_ARRAY) {
zval *data;
zend_string *key;
int i, n;
has_cookies = 1;
n = zend_hash_num_elements(Z_ARRVAL_P(cookies));
if (n > 0) {
zend_hash_internal_pointer_reset(Z_ARRVAL_P(cookies));
smart_str_append_const(&soap_headers, "Cookie: ");
for (i = 0; i < n; i++) {
zend_ulong numindx;
int res = zend_hash_get_current_key(Z_ARRVAL_P(cookies), &key, &numindx);
data = zend_hash_get_current_data(Z_ARRVAL_P(cookies));
if (res == HASH_KEY_IS_STRING && Z_TYPE_P(data) == IS_ARRAY) {
zval *value;
if ((value = zend_hash_index_find(Z_ARRVAL_P(data), 0)) != NULL &&
Z_TYPE_P(value) == IS_STRING) {
zval *tmp;
if (((tmp = zend_hash_index_find(Z_ARRVAL_P(data), 1)) == NULL ||
strncmp(phpurl->path?phpurl->path:"/",Z_STRVAL_P(tmp),Z_STRLEN_P(tmp)) == 0) &&
((tmp = zend_hash_index_find(Z_ARRVAL_P(data), 2)) == NULL ||
in_domain(phpurl->host,Z_STRVAL_P(tmp))) &&
(use_ssl || (tmp = zend_hash_index_find(Z_ARRVAL_P(data), 3)) == NULL)) {
smart_str_append(&soap_headers, key);
smart_str_appendc(&soap_headers, ';');
}
}
}
zend_hash_move_forward(Z_ARRVAL_P(cookies));
}
smart_str_append_const(&soap_headers, "\r\n");
}
}
http_context_headers(context, has_authorization, has_proxy_authorization, has_cookies, &soap_headers);
smart_str_append_const(&soap_headers, "\r\n");
smart_str_0(&soap_headers);
if ((trace = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "trace", sizeof("trace")-1)) != NULL &&
(Z_TYPE_P(trace) == IS_TRUE || (Z_TYPE_P(trace) == IS_LONG && Z_LVAL_P(trace) != 0))) {
add_property_stringl(this_ptr, "__last_request_headers", ZSTR_VAL(soap_headers.s), ZSTR_LEN(soap_headers.s));
}
smart_str_appendl(&soap_headers, request->val, request->len);
smart_str_0(&soap_headers);
err = php_stream_write(stream, ZSTR_VAL(soap_headers.s), ZSTR_LEN(soap_headers.s));
if (err != ZSTR_LEN(soap_headers.s)) {
if (request != buf) {
zend_string_release(request);
}
php_stream_close(stream);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
add_soap_fault(this_ptr, "HTTP", "Failed Sending HTTP SOAP request", NULL, NULL);
smart_str_free(&soap_headers_z);
return FALSE;
}
smart_str_free(&soap_headers);
} else {
add_soap_fault(this_ptr, "HTTP", "Failed to create stream??", NULL, NULL);
smart_str_free(&soap_headers_z);
return FALSE;
}
if (!return_value) {
php_stream_close(stream);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
smart_str_free(&soap_headers_z);
return TRUE;
}
do {
http_headers = get_http_headers(stream);
if (!http_headers) {
if (request != buf) {
zend_string_release(request);
}
php_stream_close(stream);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
add_soap_fault(this_ptr, "HTTP", "Error Fetching http headers", NULL, NULL);
smart_str_free(&soap_headers_z);
return FALSE;
}
if ((trace = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "trace", sizeof("trace")-1)) != NULL &&
(Z_TYPE_P(trace) == IS_TRUE || (Z_TYPE_P(trace) == IS_LONG && Z_LVAL_P(trace) != 0))) {
add_property_str(this_ptr, "__last_response_headers", zend_string_copy(http_headers));
}
/* Check to see what HTTP status was sent */
http_1_1 = 0;
http_status = 0;
http_version = get_http_header_value(ZSTR_VAL(http_headers), "HTTP/");
if (http_version) {
char *tmp;
if (!strncmp(http_version,"1.1", 3)) {
http_1_1 = 1;
}
tmp = strstr(http_version," ");
if (tmp != NULL) {
tmp++;
http_status = atoi(tmp);
}
tmp = strstr(tmp," ");
if (tmp != NULL) {
tmp++;
if (http_msg) {
efree(http_msg);
}
http_msg = estrdup(tmp);
}
efree(http_version);
/* Try and get headers again */
if (http_status == 100) {
zend_string_release(http_headers);
}
}
} while (http_status == 100);
/* Grab and send back every cookie */
/* Not going to worry about Path: because
we shouldn't be changing urls so path dont
matter too much
*/
cookie_itt = strstr(ZSTR_VAL(http_headers), "Set-Cookie: ");
while (cookie_itt) {
char *cookie;
char *eqpos, *sempos;
zval *cookies;
if ((cookies = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_cookies", sizeof("_cookies")-1)) == NULL ||
Z_TYPE_P(cookies) != IS_ARRAY) {
zval tmp_cookies;
array_init(&tmp_cookies);
cookies = zend_hash_str_update(Z_OBJPROP_P(this_ptr), "_cookies", sizeof("_cookies")-1, &tmp_cookies);
}
cookie = get_http_header_value(cookie_itt,"Set-Cookie: ");
eqpos = strstr(cookie, "=");
sempos = strstr(cookie, ";");
if (eqpos != NULL && (sempos == NULL || sempos > eqpos)) {
smart_str name = {0};
int cookie_len;
zval zcookie;
if (sempos != NULL) {
cookie_len = sempos-(eqpos+1);
} else {
cookie_len = strlen(cookie)-(eqpos-cookie)-1;
}
smart_str_appendl(&name, cookie, eqpos - cookie);
smart_str_0(&name);
array_init(&zcookie);
add_index_stringl(&zcookie, 0, eqpos + 1, cookie_len);
if (sempos != NULL) {
char *options = cookie + cookie_len+1;
while (*options) {
while (*options == ' ') {options++;}
sempos = strstr(options, ";");
if (strstr(options,"path=") == options) {
eqpos = options + sizeof("path=")-1;
add_index_stringl(&zcookie, 1, eqpos, sempos?(sempos-eqpos):strlen(eqpos));
} else if (strstr(options,"domain=") == options) {
eqpos = options + sizeof("domain=")-1;
add_index_stringl(&zcookie, 2, eqpos, sempos?(sempos-eqpos):strlen(eqpos));
} else if (strstr(options,"secure") == options) {
add_index_bool(&zcookie, 3, 1);
}
if (sempos != NULL) {
options = sempos+1;
} else {
break;
}
}
}
if (!zend_hash_index_exists(Z_ARRVAL(zcookie), 1)) {
char *t = phpurl->path?phpurl->path:"/";
char *c = strrchr(t, '/');
if (c) {
add_index_stringl(&zcookie, 1, t, c-t);
}
}
if (!zend_hash_index_exists(Z_ARRVAL(zcookie), 2)) {
add_index_string(&zcookie, 2, phpurl->host);
}
zend_symtable_update(Z_ARRVAL_P(cookies), name.s, &zcookie);
smart_str_free(&name);
}
cookie_itt = strstr(cookie_itt + sizeof("Set-Cookie: "), "Set-Cookie: ");
efree(cookie);
}
/* See if the server requested a close */
if (http_1_1) {
http_close = FALSE;
if (use_proxy && !use_ssl) {
connection = get_http_header_value(ZSTR_VAL(http_headers), "Proxy-Connection: ");
if (connection) {
if (strncasecmp(connection, "close", sizeof("close")-1) == 0) {
http_close = TRUE;
}
efree(connection);
}
}
if (http_close == FALSE) {
connection = get_http_header_value(ZSTR_VAL(http_headers), "Connection: ");
if (connection) {
if (strncasecmp(connection, "close", sizeof("close")-1) == 0) {
http_close = TRUE;
}
efree(connection);
}
}
} else {
http_close = TRUE;
if (use_proxy && !use_ssl) {
connection = get_http_header_value(ZSTR_VAL(http_headers), "Proxy-Connection: ");
if (connection) {
if (strncasecmp(connection, "Keep-Alive", sizeof("Keep-Alive")-1) == 0) {
http_close = FALSE;
}
efree(connection);
}
}
if (http_close == TRUE) {
connection = get_http_header_value(ZSTR_VAL(http_headers), "Connection: ");
if (connection) {
if (strncasecmp(connection, "Keep-Alive", sizeof("Keep-Alive")-1) == 0) {
http_close = FALSE;
}
efree(connection);
}
}
}
http_body = get_http_body(stream, http_close, ZSTR_VAL(http_headers));
if (!http_body) {
if (request != buf) {
zend_string_release(request);
}
php_stream_close(stream);
zend_string_release(http_headers);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
add_soap_fault(this_ptr, "HTTP", "Error Fetching http body, No Content-Length, connection closed or chunked data", NULL, NULL);
if (http_msg) {
efree(http_msg);
}
smart_str_free(&soap_headers_z);
return FALSE;
}
if (request != buf) {
zend_string_release(request);
}
if (http_close) {
php_stream_close(stream);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
stream = NULL;
}
/* Process HTTP status codes */
if (http_status >= 300 && http_status < 400) {
char *loc;
if ((loc = get_http_header_value(ZSTR_VAL(http_headers), "Location: ")) != NULL) {
php_url *new_url = php_url_parse(loc);
if (new_url != NULL) {
zend_string_release(http_headers);
zend_string_release(http_body);
efree(loc);
if (new_url->scheme == NULL && new_url->path != NULL) {
new_url->scheme = phpurl->scheme ? estrdup(phpurl->scheme) : NULL;
new_url->host = phpurl->host ? estrdup(phpurl->host) : NULL;
new_url->port = phpurl->port;
if (new_url->path && new_url->path[0] != '/') {
if (phpurl->path) {
char *t = phpurl->path;
char *p = strrchr(t, '/');
if (p) {
char *s = emalloc((p - t) + strlen(new_url->path) + 2);
strncpy(s, t, (p - t) + 1);
s[(p - t) + 1] = 0;
strcat(s, new_url->path);
efree(new_url->path);
new_url->path = s;
}
} else {
char *s = emalloc(strlen(new_url->path) + 2);
s[0] = '/'; s[1] = 0;
strcat(s, new_url->path);
efree(new_url->path);
new_url->path = s;
}
}
}
phpurl = new_url;
if (--redirect_max < 1) {
add_soap_fault(this_ptr, "HTTP", "Redirection limit reached, aborting", NULL, NULL);
smart_str_free(&soap_headers_z);
return FALSE;
}
goto try_again;
}
}
} else if (http_status == 401) {
/* Digest authentication */
zval *digest, *login, *password;
char *auth = get_http_header_value(ZSTR_VAL(http_headers), "WWW-Authenticate: ");
if (auth &&
strstr(auth, "Digest") == auth &&
((digest = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest")-1)) == NULL ||
Z_TYPE_P(digest) != IS_ARRAY) &&
(login = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login")-1)) != NULL &&
Z_TYPE_P(login) == IS_STRING &&
(password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password")-1)) != NULL &&
Z_TYPE_P(password) == IS_STRING) {
char *s;
zval digest;
ZVAL_UNDEF(&digest);
s = auth + sizeof("Digest")-1;
while (*s != '\0') {
char *name, *val;
while (*s == ' ') ++s;
name = s;
while (*s != '\0' && *s != '=') ++s;
if (*s == '=') {
*s = '\0';
++s;
if (*s == '"') {
++s;
val = s;
while (*s != '\0' && *s != '"') ++s;
} else {
val = s;
while (*s != '\0' && *s != ' ' && *s != ',') ++s;
}
if (*s != '\0') {
if (*s != ',') {
*s = '\0';
++s;
while (*s != '\0' && *s != ',') ++s;
if (*s != '\0') ++s;
} else {
*s = '\0';
++s;
}
}
if (Z_TYPE(digest) == IS_UNDEF) {
array_init(&digest);
}
add_assoc_string(&digest, name, val);
}
}
if (Z_TYPE(digest) != IS_UNDEF) {
php_url *new_url = emalloc(sizeof(php_url));
Z_DELREF(digest);
add_property_zval_ex(this_ptr, "_digest", sizeof("_digest")-1, &digest);
*new_url = *phpurl;
if (phpurl->scheme) phpurl->scheme = estrdup(phpurl->scheme);
if (phpurl->user) phpurl->user = estrdup(phpurl->user);
if (phpurl->pass) phpurl->pass = estrdup(phpurl->pass);
if (phpurl->host) phpurl->host = estrdup(phpurl->host);
if (phpurl->path) phpurl->path = estrdup(phpurl->path);
if (phpurl->query) phpurl->query = estrdup(phpurl->query);
if (phpurl->fragment) phpurl->fragment = estrdup(phpurl->fragment);
phpurl = new_url;
efree(auth);
zend_string_release(http_headers);
zend_string_release(http_body);
goto try_again;
}
}
if (auth) efree(auth);
}
smart_str_free(&soap_headers_z);
/* Check and see if the server even sent a xml document */
content_type = get_http_header_value(ZSTR_VAL(http_headers), "Content-Type: ");
if (content_type) {
char *pos = NULL;
int cmplen;
pos = strstr(content_type,";");
if (pos != NULL) {
cmplen = pos - content_type;
} else {
cmplen = strlen(content_type);
}
if (strncmp(content_type, "text/xml", cmplen) == 0 ||
strncmp(content_type, "application/soap+xml", cmplen) == 0) {
content_type_xml = 1;
/*
if (strncmp(http_body, "<?xml", 5)) {
zval *err;
MAKE_STD_ZVAL(err);
ZVAL_STRINGL(err, http_body, http_body_size, 1);
add_soap_fault(this_ptr, "HTTP", "Didn't receive an xml document", NULL, err);
efree(content_type);
zend_string_release(http_headers);
efree(http_body);
return FALSE;
}
*/
}
efree(content_type);
}
/* Decompress response */
content_encoding = get_http_header_value(ZSTR_VAL(http_headers), "Content-Encoding: ");
if (content_encoding) {
zval func;
zval retval;
zval params[1];
if ((strcmp(content_encoding,"gzip") == 0 ||
strcmp(content_encoding,"x-gzip") == 0) &&
zend_hash_str_exists(EG(function_table), "gzinflate", sizeof("gzinflate")-1)) {
ZVAL_STRING(&func, "gzinflate");
ZVAL_STRINGL(¶ms[0], http_body->val+10, http_body->len-10);
} else if (strcmp(content_encoding,"deflate") == 0 &&
zend_hash_str_exists(EG(function_table), "gzuncompress", sizeof("gzuncompress")-1)) {
ZVAL_STRING(&func, "gzuncompress");
ZVAL_STR_COPY(¶ms[0], http_body);
} else {
efree(content_encoding);
zend_string_release(http_headers);
zend_string_release(http_body);
if (http_msg) {
efree(http_msg);
}
add_soap_fault(this_ptr, "HTTP", "Unknown Content-Encoding", NULL, NULL);
return FALSE;
}
if (call_user_function(CG(function_table), (zval*)NULL, &func, &retval, 1, params) == SUCCESS &&
Z_TYPE(retval) == IS_STRING) {
zval_ptr_dtor(¶ms[0]);
zval_ptr_dtor(&func);
zend_string_release(http_body);
ZVAL_COPY_VALUE(return_value, &retval);
} else {
zval_ptr_dtor(¶ms[0]);
zval_ptr_dtor(&func);
efree(content_encoding);
zend_string_release(http_headers);
zend_string_release(http_body);
add_soap_fault(this_ptr, "HTTP", "Can't uncompress compressed response", NULL, NULL);
if (http_msg) {
efree(http_msg);
}
return FALSE;
}
efree(content_encoding);
} else {
ZVAL_STR(return_value, http_body);
}
zend_string_release(http_headers);
if (http_status >= 400) {
int error = 0;
if (Z_STRLEN_P(return_value) == 0) {
error = 1;
} else if (Z_STRLEN_P(return_value) > 0) {
if (!content_type_xml) {
char *s = Z_STRVAL_P(return_value);
while (*s != '\0' && *s < ' ') {
s++;
}
if (strncmp(s, "<?xml", 5)) {
error = 1;
}
}
}
if (error) {
zval_ptr_dtor(return_value);
ZVAL_UNDEF(return_value);
add_soap_fault(this_ptr, "HTTP", http_msg, NULL, NULL);
efree(http_msg);
return FALSE;
}
}
if (http_msg) {
efree(http_msg);
}
return TRUE;
}
|
CWE-20
| 178,332 | 10,404 |
317971131264967414317960559069501027834
| null | null | null |
php
|
a6fdc5bb27b20d889de0cd29318b3968aabb57bd
| 1 |
int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */
{
phar_zip_dir_end locator;
char buf[sizeof(locator) + 65536];
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 (!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) TSRMLS_CC) == FAILURE) {
mydata->metadata_len = 0;
/* if not valid serialized data, it is a regular string */
if (entry.is_persistent) {
ALLOC_PERMANENT_ZVAL(mydata->metadata);
} else {
ALLOC_ZVAL(mydata->metadata);
}
INIT_ZVAL(*mydata->metadata);
metadata = pestrndup(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent);
ZVAL_STRINGL(mydata->metadata, metadata, PHAR_GET_16(locator.comment_len), 0);
}
} else {
mydata->metadata = NULL;
}
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.arBuckets = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.arBuckets = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.arBuckets = 0; \
php_stream_close(fp); \
if (mydata->metadata) { \
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.arBuckets = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.arBuckets = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.arBuckets = 0; \
php_stream_close(fp); \
if (mydata->metadata) { \
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;
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;
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 */
phar_stream_copy_to_stream(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 */
phar_stream_copy_to_stream(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 TSRMLS_CC)) {
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 TSRMLS_CC);
if (PHAR_GET_16(zipentry.extra_len)) {
off_t loc = php_stream_tell(fp);
if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len) TSRMLS_CC)) {
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) TSRMLS_CC) == FAILURE) {
entry.metadata_len = 0;
/* if not valid serialized data, it is a regular string */
if (entry.is_persistent) {
ALLOC_PERMANENT_ZVAL(entry.metadata);
} else {
ALLOC_ZVAL(entry.metadata);
}
INIT_ZVAL(*entry.metadata);
ZVAL_STRINGL(entry.metadata, pestrndup(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent), PHAR_GET_16(zipentry.comment_len), 0);
}
} else {
entry.metadata = NULL;
}
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;
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) TSRMLS_CC);
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);
if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !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 TSRMLS_CC);
} else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) {
filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC);
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);
if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !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 TSRMLS_CC);
} else {
if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !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 TSRMLS_CC);
zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry,sizeof(phar_entry_info), NULL);
}
mydata->fp = fp;
if (zend_hash_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
mydata->is_data = 0;
} else {
mydata->is_data = 1;
}
zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
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_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len);
return FAILURE;
}
mydata->is_temporary_alias = 0;
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, mydata->alias_len TSRMLS_CC)) {
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_del(&(PHAR_GLOBALS->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_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
} else {
phar_archive_data **fd_ptr;
if (alias_len) {
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) {
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_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len);
return FAILURE;
}
}
zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
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
| 178,335 | 10,405 |
65471772141960577329587235260095087332
| null | null | null |
php
|
b1bd4119bcafab6f9a8f84d92cd65eec3afeface
| 1 |
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->type == ST_FIELD && ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
|
CWE-119
| 178,337 | 10,407 |
200307410240704806981868673038580836943
| null | null | null |
qemu
|
415ab35a441eca767d033a2702223e785b9d5190
| 1 |
static int ne2000_buffer_full(NE2000State *s)
{
int avail, index, boundary;
index = s->curpag << 8;
boundary = s->boundary << 8;
if (index < boundary)
return 1;
return 0;
}
|
CWE-20
| 178,356 | 10,412 |
251741541197334487126568870857316605986
| null | null | null |
qemu
|
fe3c546c5ff2a6210f9a4d8561cc64051ca8603e
| 1 |
static int rndis_query_response(USBNetState *s,
rndis_query_msg_type *buf, unsigned int length)
{
rndis_query_cmplt_type *resp;
/* oid_supported_list is the largest data reply */
uint8_t infobuf[sizeof(oid_supported_list)];
uint32_t bufoffs, buflen;
int infobuflen;
unsigned int resplen;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (bufoffs + buflen > length)
return USB_RET_STALL;
infobuflen = ndis_query(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen, infobuf,
resplen = sizeof(rndis_query_cmplt_type) +
((infobuflen < 0) ? 0 : infobuflen);
resp = rndis_queue_response(s, resplen);
if (!resp)
return USB_RET_STALL;
resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT);
resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
resp->MessageLength = cpu_to_le32(resplen);
if (infobuflen < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
resp->InformationBufferLength = cpu_to_le32(0);
resp->InformationBufferOffset = cpu_to_le32(0);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
resp->InformationBufferOffset =
cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0);
resp->InformationBufferLength = cpu_to_le32(infobuflen);
memcpy(resp + 1, infobuf, infobuflen);
return 0;
}
|
CWE-189
| 178,357 | 10,413 |
35868650006871746007884459259388384254
| null | null | null |
qemu
|
fe3c546c5ff2a6210f9a4d8561cc64051ca8603e
| 1 |
static int rndis_set_response(USBNetState *s,
rndis_set_msg_type *buf, unsigned int length)
{
rndis_set_cmplt_type *resp =
rndis_queue_response(s, sizeof(rndis_set_cmplt_type));
uint32_t bufoffs, buflen;
int ret;
if (!resp)
return USB_RET_STALL;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (bufoffs + buflen > length)
return USB_RET_STALL;
ret = ndis_set(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen);
resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type));
if (ret < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
return 0;
}
|
CWE-189
| 178,358 | 10,414 |
11035841434505204682385490214301101275
| null | null | null |
qemu
|
80eecda8e5d09c442c24307f340840a5b70ea3b9
| 1 |
static int is_rndis(USBNetState *s)
{
return s->dev.config->bConfigurationValue == DEV_RNDIS_CONFIG_VALUE;
}
| 178,359 | 10,415 |
249542340550780968243494844848235251941
| null | null | null |
|
qemu
|
fa1298c2d623522eda7b4f1f721fcb935abb7360
| 1 |
static int ohci_bus_start(OHCIState *ohci)
{
ohci->eof_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
ohci_frame_boundary,
ohci);
if (ohci->eof_timer == NULL) {
trace_usb_ohci_bus_eof_timer_failed(ohci->name);
ohci_die(ohci);
return 0;
}
trace_usb_ohci_start(ohci->name);
/* Delay the first SOF event by one frame time as
if (ohci->eof_timer == NULL) {
trace_usb_ohci_bus_eof_timer_failed(ohci->name);
ohci_die(ohci);
return 0;
}
trace_usb_ohci_start(ohci->name);
/* Delay the first SOF event by one frame time as
static void ohci_bus_stop(OHCIState *ohci)
{
trace_usb_ohci_stop(ohci->name);
if (ohci->eof_timer) {
timer_del(ohci->eof_timer);
timer_free(ohci->eof_timer);
}
ohci->eof_timer = NULL;
}
/* Sets a flag in a port status register but only set it if the port is
}
| 178,360 | 10,416 |
144737052562192971545349321992556721527
| null | null | null |
|
qemu
|
da885fe1ee8b4589047484bd7fa05a4905b52b17
| 1 |
void *load_device_tree(const char *filename_path, int *sizep)
{
int dt_size;
int dt_file_load_size;
int ret;
void *fdt = NULL;
*sizep = 0;
dt_size = get_image_size(filename_path);
if (dt_size < 0) {
error_report("Unable to get size of device tree file '%s'",
filename_path);
goto fail;
}
/* Expand to 2x size to give enough room for manipulation. */
dt_size += 10000;
dt_size *= 2;
/* First allocate space in qemu for device tree */
fdt = g_malloc0(dt_size);
dt_file_load_size = load_image(filename_path, fdt);
if (dt_file_load_size < 0) {
error_report("Unable to open device tree file '%s'",
filename_path);
goto fail;
}
ret = fdt_open_into(fdt, fdt, dt_size);
if (ret) {
error_report("Unable to copy device tree in memory");
goto fail;
}
/* Check sanity of device tree */
if (fdt_check_header(fdt)) {
error_report("Device tree file loaded into memory is invalid: %s",
filename_path);
goto fail;
}
*sizep = dt_size;
return fdt;
fail:
g_free(fdt);
return NULL;
}
|
CWE-119
| 178,394 | 10,417 |
202841112256018638106918054419474957963
| null | null | null |
qemu
|
4ab0359a8ae182a7ac5c99609667273167703fab
| 1 |
static void ncq_err(NCQTransferState *ncq_tfs)
{
IDEState *ide_state = &ncq_tfs->drive->port.ifs[0];
ide_state->error = ABRT_ERR;
ide_state->status = READY_STAT | ERR_STAT;
ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag);
}
| 178,395 | 10,418 |
331729055682720746240637611988089825870
| null | null | null |
|
php
|
0e6fe3a4c96be2d3e88389a5776f878021b4c59f
| 1 |
ZEND_METHOD(CURLFile, __wakeup)
{
zend_update_property_string(curl_CURLFile_class, getThis(), "name", sizeof("name")-1, "" TSRMLS_CC);
zend_throw_exception(NULL, "Unserialization of CURLFile instances is not allowed", 0 TSRMLS_CC);
}
|
CWE-416
| 178,431 | 10,421 |
88547485324857401522585862929403733469
| null | null | null |
php
|
16023f3e3b9c06cf677c3c980e8d574e4c162827
| 1 |
PHP_FUNCTION(openssl_random_pseudo_bytes)
{
long buffer_length;
unsigned char *buffer = NULL;
zval *zstrong_result_returned = NULL;
int strong_result = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &buffer_length, &zstrong_result_returned) == FAILURE) {
return;
return;
}
if (buffer_length <= 0) {
RETURN_FALSE;
}
if (zstrong_result_returned) {
zval_dtor(zstrong_result_returned);
ZVAL_BOOL(zstrong_result_returned, 0);
}
buffer = emalloc(buffer_length + 1);
#ifdef PHP_WIN32
strong_result = 1;
/* random/urandom equivalent on Windows */
if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) {
efree(buffer);
if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) {
efree(buffer);
if (zstrong_result_returned) {
RETURN_FALSE;
}
#else
if ((strong_result = RAND_pseudo_bytes(buffer, buffer_length)) < 0) {
efree(buffer);
if (zstrong_result_returned) {
ZVAL_BOOL(zstrong_result_returned, 0);
if (zstrong_result_returned) {
ZVAL_BOOL(zstrong_result_returned, 0);
}
RETURN_FALSE;
}
#endif
RETVAL_STRINGL((char *)buffer, buffer_length, 0);
if (zstrong_result_returned) {
ZVAL_BOOL(zstrong_result_returned, strong_result);
}
}
/* }}} */
|
CWE-310
| 178,444 | 10,422 |
90247547542504229788429033891859566836
| null | null | null |
php
|
de31324c221c1791b26350ba106cc26bad23ace9
| 1 |
static PHP_RINIT_FUNCTION(libxml)
{
if (_php_libxml_per_request_initialization) {
/* report errors via handler rather than stderr */
xmlSetGenericErrorFunc(NULL, php_libxml_error_handler);
xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename);
xmlOutputBufferCreateFilenameDefault(php_libxml_output_buffer_create_filename);
}
return SUCCESS;
}
| 178,445 | 10,423 |
267259078063603499441477993651774172508
| null | null | null |
|
php
|
97aa752fee61fccdec361279adbfb17a3c60f3f4
| 1 |
mysqlnd_switch_to_ssl_if_needed(
MYSQLND_CONN_DATA * conn,
const MYSQLND_PACKET_GREET * const greet_packet,
const MYSQLND_OPTIONS * const options,
unsigned long mysql_flags
TSRMLS_DC
)
{
enum_func_status ret = FAIL;
const MYSQLND_CHARSET * charset;
MYSQLND_PACKET_AUTH * auth_packet;
DBG_ENTER("mysqlnd_switch_to_ssl_if_needed");
auth_packet = conn->protocol->m.get_auth_packet(conn->protocol, FALSE TSRMLS_CC);
if (!auth_packet) {
SET_OOM_ERROR(*conn->error_info);
goto end;
}
auth_packet->client_flags = mysql_flags;
auth_packet->max_packet_size = MYSQLND_ASSEMBLED_PACKET_MAX_SIZE;
if (options->charset_name && (charset = mysqlnd_find_charset_name(options->charset_name))) {
auth_packet->charset_no = charset->nr;
} else {
#if MYSQLND_UNICODE
auth_packet->charset_no = 200;/* utf8 - swedish collation, check mysqlnd_charset.c */
#else
auth_packet->charset_no = greet_packet->charset_no;
#endif
}
#ifdef MYSQLND_SSL_SUPPORTED
if ((greet_packet->server_capabilities & CLIENT_SSL) && (mysql_flags & CLIENT_SSL)) {
zend_bool verify = mysql_flags & CLIENT_SSL_VERIFY_SERVER_CERT? TRUE:FALSE;
DBG_INF("Switching to SSL");
if (!PACKET_WRITE(auth_packet, conn)) {
CONN_SET_STATE(conn, CONN_QUIT_SENT);
SET_CLIENT_ERROR(*conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);
goto end;
}
conn->net->m.set_client_option(conn->net, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (const char *) &verify TSRMLS_CC);
if (FAIL == conn->net->m.enable_ssl(conn->net TSRMLS_CC)) {
goto end;
}
}
#endif
ret = PASS;
end:
PACKET_FREE(auth_packet);
DBG_RETURN(ret);
}
|
CWE-284
| 178,447 | 10,425 |
296126824449519971585633370712015689883
| null | null | null |
qemu
|
156a2e4dbffa85997636a7a39ef12da6f1b40254
| 1 |
static int ehci_process_itd(EHCIState *ehci,
EHCIitd *itd,
uint32_t addr)
{
USBDevice *dev;
USBEndpoint *ep;
uint32_t i, len, pid, dir, devaddr, endp;
uint32_t pg, off, ptr1, ptr2, max, mult;
ehci->periodic_sched_active = PERIODIC_ACTIVE;
dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
for(i = 0; i < 8; i++) {
if (itd->transact[i] & ITD_XACT_ACTIVE) {
pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
off = itd->transact[i] & ITD_XACT_OFFSET_MASK;
ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK);
len = get_field(itd->transact[i], ITD_XACT_LENGTH);
if (len > max * mult) {
len = max * mult;
}
if (len > BUFF_SIZE) {
return -1;
}
qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
if (off + len > 4096) {
/* transfer crosses page border */
uint32_t len2 = off + len - 4096;
uint32_t len1 = len - len2;
qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
qemu_sglist_add(&ehci->isgl, ptr2, len2);
} else {
qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
}
pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
dev = ehci_find_device(ehci, devaddr);
ep = usb_ep_get(dev, pid, endp);
if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
(itd->transact[i] & ITD_XACT_IOC) != 0);
usb_packet_map(&ehci->ipacket, &ehci->isgl);
usb_handle_packet(dev, &ehci->ipacket);
usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
} else {
DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
ehci->ipacket.status = USB_RET_NAK;
ehci->ipacket.actual_length = 0;
}
qemu_sglist_destroy(&ehci->isgl);
switch (ehci->ipacket.status) {
case USB_RET_SUCCESS:
break;
default:
fprintf(stderr, "Unexpected iso usb result: %d\n",
ehci->ipacket.status);
/* Fall through */
case USB_RET_IOERROR:
case USB_RET_NODEV:
/* 3.3.2: XACTERR is only allowed on IN transactions */
if (dir) {
itd->transact[i] |= ITD_XACT_XACTERR;
ehci_raise_irq(ehci, USBSTS_ERRINT);
}
break;
case USB_RET_BABBLE:
itd->transact[i] |= ITD_XACT_BABBLE;
ehci_raise_irq(ehci, USBSTS_ERRINT);
break;
case USB_RET_NAK:
/* no data for us, so do a zero-length transfer */
ehci->ipacket.actual_length = 0;
break;
}
if (!dir) {
set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* OUT */
} else {
set_field(&itd->transact[i], ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* IN */
}
if (itd->transact[i] & ITD_XACT_IOC) {
ehci_raise_irq(ehci, USBSTS_INT);
}
itd->transact[i] &= ~ITD_XACT_ACTIVE;
}
}
return 0;
}
|
CWE-20
| 178,451 | 10,428 |
186685491160390428894750367344612998998
| null | null | null |
qemu
|
a890a2f9137ac3cf5b607649e66a6f3a5512d8dc
| 1 |
int virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
uint32_t num;
uint32_t features;
uint32_t supported_features;
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) {
return -1;
}
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
supported_features = k->get_features(qbus->parent);
error_report("Features 0x%x unsupported. Allowed features: 0x%x",
features, supported_features);
features, supported_features);
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
|
CWE-119
| 178,457 | 10,429 |
33588596390600101289490689353048137901
| null | null | null |
qemu
|
8b98a2f07175d46c3f7217639bd5e03f2ec56343
| 1 |
ssize_t pcnet_receive(NetClientState *nc, const uint8_t *buf, size_t size_)
{
PCNetState *s = qemu_get_nic_opaque(nc);
int is_padr = 0, is_bcast = 0, is_ladr = 0;
uint8_t buf1[60];
int remaining;
int crc_err = 0;
int size = size_;
if (CSR_DRX(s) || CSR_STOP(s) || CSR_SPND(s) || !size ||
(CSR_LOOP(s) && !s->looptest)) {
return -1;
}
#ifdef PCNET_DEBUG
printf("pcnet_receive size=%d\n", size);
#endif
/* if too small buffer, then expand it */
if (size < MIN_BUF_SIZE) {
memcpy(buf1, buf, size);
memset(buf1 + size, 0, MIN_BUF_SIZE - size);
buf = buf1;
size = MIN_BUF_SIZE;
}
if (CSR_PROM(s)
|| (is_padr=padr_match(s, buf, size))
|| (is_bcast=padr_bcast(s, buf, size))
|| (is_ladr=ladr_match(s, buf, size))) {
pcnet_rdte_poll(s);
if (!(CSR_CRST(s) & 0x8000) && s->rdra) {
struct pcnet_RMD rmd;
int rcvrc = CSR_RCVRC(s)-1,i;
hwaddr nrda;
for (i = CSR_RCVRL(s)-1; i > 0; i--, rcvrc--) {
if (rcvrc <= 1)
rcvrc = CSR_RCVRL(s);
nrda = s->rdra +
(CSR_RCVRL(s) - rcvrc) *
(BCR_SWSTYLE(s) ? 16 : 8 );
RMDLOAD(&rmd, nrda);
if (GET_FIELD(rmd.status, RMDS, OWN)) {
#ifdef PCNET_DEBUG_RMD
printf("pcnet - scan buffer: RCVRC=%d PREV_RCVRC=%d\n",
rcvrc, CSR_RCVRC(s));
#endif
CSR_RCVRC(s) = rcvrc;
pcnet_rdte_poll(s);
break;
}
}
}
if (!(CSR_CRST(s) & 0x8000)) {
#ifdef PCNET_DEBUG_RMD
printf("pcnet - no buffer: RCVRC=%d\n", CSR_RCVRC(s));
#endif
s->csr[0] |= 0x1000; /* Set MISS flag */
CSR_MISSC(s)++;
} else {
uint8_t *src = s->buffer;
hwaddr crda = CSR_CRDA(s);
struct pcnet_RMD rmd;
int pktcount = 0;
if (!s->looptest) {
memcpy(src, buf, size);
/* no need to compute the CRC */
src[size] = 0;
uint32_t fcs = ~0;
uint8_t *p = src;
while (p != &src[size])
CRC(fcs, *p++);
*(uint32_t *)p = htonl(fcs);
size += 4;
} else {
uint32_t fcs = ~0;
uint8_t *p = src;
while (p != &src[size])
CRC(fcs, *p++);
crc_err = (*(uint32_t *)p != htonl(fcs));
}
#ifdef PCNET_DEBUG_MATCH
PRINT_PKTHDR(buf);
#endif
RMDLOAD(&rmd, PHYSADDR(s,crda));
/*if (!CSR_LAPPEN(s))*/
SET_FIELD(&rmd.status, RMDS, STP, 1);
#define PCNET_RECV_STORE() do { \
int count = MIN(4096 - GET_FIELD(rmd.buf_length, RMDL, BCNT),remaining); \
hwaddr rbadr = PHYSADDR(s, rmd.rbadr); \
s->phys_mem_write(s->dma_opaque, rbadr, src, count, CSR_BSWP(s)); \
src += count; remaining -= count; \
SET_FIELD(&rmd.status, RMDS, OWN, 0); \
RMDSTORE(&rmd, PHYSADDR(s,crda)); \
pktcount++; \
} while (0)
remaining = size;
PCNET_RECV_STORE();
if ((remaining > 0) && CSR_NRDA(s)) {
hwaddr nrda = CSR_NRDA(s);
#ifdef PCNET_DEBUG_RMD
PRINT_RMD(&rmd);
#endif
RMDLOAD(&rmd, PHYSADDR(s,nrda));
if (GET_FIELD(rmd.status, RMDS, OWN)) {
crda = nrda;
PCNET_RECV_STORE();
#ifdef PCNET_DEBUG_RMD
PRINT_RMD(&rmd);
#endif
if ((remaining > 0) && (nrda=CSR_NNRD(s))) {
RMDLOAD(&rmd, PHYSADDR(s,nrda));
if (GET_FIELD(rmd.status, RMDS, OWN)) {
crda = nrda;
PCNET_RECV_STORE();
}
}
}
}
#undef PCNET_RECV_STORE
RMDLOAD(&rmd, PHYSADDR(s,crda));
if (remaining == 0) {
SET_FIELD(&rmd.msg_length, RMDM, MCNT, size);
SET_FIELD(&rmd.status, RMDS, ENP, 1);
SET_FIELD(&rmd.status, RMDS, PAM, !CSR_PROM(s) && is_padr);
SET_FIELD(&rmd.status, RMDS, LFAM, !CSR_PROM(s) && is_ladr);
SET_FIELD(&rmd.status, RMDS, BAM, !CSR_PROM(s) && is_bcast);
if (crc_err) {
SET_FIELD(&rmd.status, RMDS, CRC, 1);
SET_FIELD(&rmd.status, RMDS, ERR, 1);
}
} else {
SET_FIELD(&rmd.status, RMDS, OFLO, 1);
SET_FIELD(&rmd.status, RMDS, BUFF, 1);
SET_FIELD(&rmd.status, RMDS, ERR, 1);
}
RMDSTORE(&rmd, PHYSADDR(s,crda));
s->csr[0] |= 0x0400;
#ifdef PCNET_DEBUG
printf("RCVRC=%d CRDA=0x%08x BLKS=%d\n",
CSR_RCVRC(s), PHYSADDR(s,CSR_CRDA(s)), pktcount);
#endif
#ifdef PCNET_DEBUG_RMD
PRINT_RMD(&rmd);
#endif
while (pktcount--) {
if (CSR_RCVRC(s) <= 1)
CSR_RCVRC(s) = CSR_RCVRL(s);
else
CSR_RCVRC(s)--;
}
pcnet_rdte_poll(s);
}
}
pcnet_poll(s);
pcnet_update_irq(s);
return size_;
}
|
CWE-119
| 178,458 | 10,430 |
296112816119408608265184776938667063138
| null | null | null |
php
|
bf58162ddf970f63502837f366930e44d6a992cf
| 1 |
PHP_METHOD(Phar, webPhar)
{
zval *mimeoverride = NULL, *rewrite = NULL;
char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL;
int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0;
char *fname, *path_info, *mime_type = NULL, *entry, *pt;
const char *basename;
int fname_len, entry_len, code, index_php_len = 0, not_cgi;
phar_archive_data *phar = NULL;
phar_entry_info *info = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!saz", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
fname = (char*)zend_get_executed_filename(TSRMLS_C);
fname_len = strlen(fname);
if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
return;
}
/* retrieve requested file within phar */
if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, "GET") || !strcmp(SG(request_info).request_method, "POST")))) {
return;
}
#ifdef PHP_WIN32
fname = estrndup(fname, fname_len);
phar_unixify_path_separators(fname, fname_len);
#endif
basename = zend_memrchr(fname, '/', fname_len);
if (!basename) {
basename = fname;
} else {
++basename;
}
if ((strlen(sapi_module.name) == sizeof("cgi-fcgi")-1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi")-1))
|| (strlen(sapi_module.name) == sizeof("fpm-fcgi")-1 && !strncmp(sapi_module.name, "fpm-fcgi", sizeof("fpm-fcgi")-1))
|| (strlen(sapi_module.name) == sizeof("cgi")-1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi")-1))) {
if (PG(http_globals)[TRACK_VARS_SERVER]) {
HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]);
zval **z_script_name, **z_path_info;
if (SUCCESS != zend_hash_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void**)&z_script_name) ||
IS_STRING != Z_TYPE_PP(z_script_name) ||
!strstr(Z_STRVAL_PP(z_script_name), basename)) {
return;
}
if (SUCCESS == zend_hash_find(_server, "PATH_INFO", sizeof("PATH_INFO"), (void**)&z_path_info) &&
IS_STRING == Z_TYPE_PP(z_path_info)) {
entry_len = Z_STRLEN_PP(z_path_info);
entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len);
path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1);
memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1);
free_pathinfo = 1;
} else {
entry_len = 0;
entry = estrndup("", 0);
path_info = Z_STRVAL_PP(z_script_name);
}
pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
} else {
char *testit;
testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC);
if (!(pt = strstr(testit, basename))) {
efree(testit);
return;
}
path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC);
if (path_info) {
entry = path_info;
entry_len = strlen(entry);
spprintf(&path_info, 0, "%s%s", testit, path_info);
free_pathinfo = 1;
} else {
path_info = testit;
free_pathinfo = 1;
entry = estrndup("", 0);
entry_len = 0;
}
pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname)));
}
not_cgi = 0;
} else {
path_info = SG(request_info).request_uri;
if (!(pt = strstr(path_info, basename))) {
/* this can happen with rewrite rules - and we have no idea what to do then, so return */
return;
}
entry_len = strlen(path_info);
entry_len -= (pt - path_info) + (fname_len - (basename - fname));
entry = estrndup(pt + (fname_len - (basename - fname)), entry_len);
pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname)));
not_cgi = 1;
}
if (rewrite) {
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval *params, *retval_ptr, **zp[1];
MAKE_STD_ZVAL(params);
ZVAL_STRINGL(params, entry, entry_len, 1);
zp[0] = ¶ms;
#if PHP_VERSION_ID < 50300
if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) {
#else
if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) {
#endif
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: invalid rewrite callback");
if (free_pathinfo) {
efree(path_info);
}
return;
}
fci.param_count = 1;
fci.params = zp;
#if PHP_VERSION_ID < 50300
++(params->refcount);
#else
Z_ADDREF_P(params);
#endif
fci.retval_ptr_ptr = &retval_ptr;
if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) {
if (!EG(exception)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: failed to call rewrite callback");
}
if (free_pathinfo) {
efree(path_info);
}
return;
}
if (!fci.retval_ptr_ptr || !retval_ptr) {
if (free_pathinfo) {
efree(path_info);
}
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
return;
}
switch (Z_TYPE_P(retval_ptr)) {
#if PHP_VERSION_ID >= 60000
case IS_UNICODE:
zval_unicode_to_string(retval_ptr TSRMLS_CC);
/* break intentionally omitted */
#endif
case IS_STRING:
efree(entry);
if (fci.retval_ptr_ptr != &retval_ptr) {
entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr));
entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr);
} else {
entry = Z_STRVAL_P(retval_ptr);
entry_len = Z_STRLEN_P(retval_ptr);
}
break;
case IS_BOOL:
phar_do_403(entry, entry_len TSRMLS_CC);
if (free_pathinfo) {
efree(path_info);
}
zend_bailout();
return;
default:
efree(retval_ptr);
if (free_pathinfo) {
efree(path_info);
}
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
return;
}
}
if (entry_len) {
phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC);
}
if (!entry_len || (entry_len == 1 && entry[0] == '/')) {
efree(entry);
/* direct request */
if (index_php_len) {
entry = index_php;
entry_len = index_php_len;
if (entry[0] != '/') {
spprintf(&entry, 0, "/%s", index_php);
++entry_len;
}
} else {
/* assume "index.php" is starting point */
entry = estrndup("/index.php", sizeof("/index.php"));
entry_len = sizeof("/index.php")-1;
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
if (free_pathinfo) {
efree(path_info);
}
zend_bailout();
} else {
char *tmp = NULL, sa = '\0';
sapi_header_line ctr = {0};
ctr.response_code = 301;
ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")-1;
ctr.line = "HTTP/1.1 301 Moved Permanently";
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
if (not_cgi) {
tmp = strstr(path_info, basename) + fname_len;
sa = *tmp;
*tmp = '\0';
}
ctr.response_code = 0;
if (path_info[strlen(path_info)-1] == '/') {
ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry + 1);
} else {
ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry);
}
if (not_cgi) {
*tmp = sa;
}
if (free_pathinfo) {
efree(path_info);
}
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
sapi_send_headers(TSRMLS_C);
efree(ctr.line);
zend_bailout();
}
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
#ifdef PHP_WIN32
efree(fname);
#endif
zend_bailout();
}
if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) {
const char *ext = zend_memrchr(entry, '.', entry_len);
zval **val;
if (ext) {
++ext;
if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) {
switch (Z_TYPE_PP(val)) {
case IS_LONG:
if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) {
mime_type = "";
code = Z_LVAL_PP(val);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed");
#ifdef PHP_WIN32
efree(fname);
#endif
RETURN_FALSE;
}
break;
case IS_STRING:
mime_type = Z_STRVAL_PP(val);
code = PHAR_MIME_OTHER;
break;
default:
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed");
#ifdef PHP_WIN32
efree(fname);
#endif
RETURN_FALSE;
}
}
}
}
if (!mime_type) {
code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC);
}
ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC);
}
/* }}} */
/* {{{ proto void Phar::mungServer(array munglist)
* Defines a list of up to 4 $_SERVER variables that should be modified for execution
* to mask the presence of the phar archive. This should be used in conjunction with
* Phar::webPhar(), and has no effect otherwise
* SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME
*/
PHP_METHOD(Phar, mungServer)
{
zval *mungvalues;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &mungvalues) == FAILURE) {
return;
}
if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
phar_request_initialize(TSRMLS_C);
for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) {
zval **data = NULL;
if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to retrieve array value in Phar::mungServer()");
return;
}
if (Z_TYPE_PP(data) != IS_STRING) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
if (Z_STRLEN_PP(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_PP(data), "PHP_SELF", sizeof("PHP_SELF")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF;
}
if (Z_STRLEN_PP(data) == sizeof("REQUEST_URI")-1) {
if (!strncmp(Z_STRVAL_PP(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI;
}
if (!strncmp(Z_STRVAL_PP(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME;
}
}
if (Z_STRLEN_PP(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_PP(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME;
}
}
}
/* }}} */
/* {{{ proto void Phar::interceptFileFuncs()
* instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
* and return stat on files within the phar for relative paths
*
* Once called, this cannot be reversed, and continue until the end of the request.
*
* This allows legacy scripts to be pharred unmodified
*/
PHP_METHOD(Phar, interceptFileFuncs)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
phar_intercept_functions(TSRMLS_C);
}
/* }}} */
/* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]])
* Return a stub that can be used to run a phar-based archive without the phar extension
* indexfile is the CLI startup filename, which defaults to "index.php", webindexfile
* is the web startup filename, and also defaults to "index.php"
*/
PHP_METHOD(Phar, createDefaultStub)
{
char *index = NULL, *webindex = NULL, *stub, *error;
int index_len = 0, webindex_len = 0;
size_t stub_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
return;
}
stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
return;
}
RETURN_STRINGL(stub, stub_len, 0);
}
/* }}} */
/* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]])
* Reads the currently executed file (a phar) and registers its manifest */
PHP_METHOD(Phar, mapPhar)
{
char *alias = NULL, *error;
int alias_len = 0;
long dataoffset = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} /* }}} */
/* {{{ proto mixed Phar::loadPhar(string filename [, string alias])
* Loads any phar archive with an alias */
PHP_METHOD(Phar, loadPhar)
{
char *fname, *alias = NULL, *error;
int fname_len, alias_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} /* }}} */
/* {{{ proto string Phar::apiVersion()
* Returns the api version */
PHP_METHOD(Phar, apiVersion)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1);
}
/* }}}*/
/* {{{ proto bool Phar::canCompress([int method])
* Returns whether phar extension supports compression using zlib/bzip2 */
PHP_METHOD(Phar, canCompress)
{
long method = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
switch (method) {
case PHAR_ENT_COMPRESSED_GZ:
if (PHAR_G(has_zlib)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
case PHAR_ENT_COMPRESSED_BZ2:
if (PHAR_G(has_bz2)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
default:
if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
}
/* }}} */
/* {{{ proto bool Phar::canWrite()
* Returns whether phar extension supports writing and creating phars */
PHP_METHOD(Phar, canWrite)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(!PHAR_G(readonly));
}
/* }}} */
/* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true])
* Returns whether the given filename is a valid phar filename */
PHP_METHOD(Phar, isValidPharFilename)
{
char *fname;
const char *ext_str;
int fname_len, ext_len, is_executable;
zend_bool executable = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &fname, &fname_len, &executable) == FAILURE) {
return;
}
is_executable = executable;
RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS);
}
/* }}} */
#if HAVE_SPL
/**
* from spl_directory
*/
static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar = (phar_archive_data *) object->oth;
if (!phar->is_persistent) {
phar_archive_delref(phar TSRMLS_CC);
}
object->oth = NULL;
}
/* }}} */
/**
* from spl_directory
*/
static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar_data = (phar_archive_data *) dst->oth;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
}
/* }}} */
static spl_other_handler phar_spl_foreign_handler = {
phar_spl_foreign_dtor,
phar_spl_foreign_clone
};
#endif /* HAVE_SPL */
/* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]])
* Construct a Phar archive object
*
* proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR])
* Construct a PharData archive object
*
* This function is used as the constructor for both the Phar and PharData
* classes, hence the two prototypes above.
*/
PHP_METHOD(Phar, __construct)
{
#if !HAVE_SPL
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension");
#else
char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname;
int fname_len, alias_len = 0, arch_len, entry_len, is_data;
#if PHP_VERSION_ID < 50300
long flags = 0;
#else
long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS;
#endif
long format = 0;
phar_archive_object *phar_obj;
phar_archive_data *phar_data;
zval *zobj = getThis(), arg1, arg2;
phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC);
if (is_data) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) {
return;
}
}
if (phar_obj->arc.archive) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice");
return;
}
save_fname = fname;
if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) {
/* use arch (the basename for the archive) for fname instead of fname */
/* this allows support for RecursiveDirectoryIterator of subdirectories */
#ifdef PHP_WIN32
phar_unixify_path_separators(arch, arch_len);
#endif
fname = arch;
fname_len = arch_len;
#ifdef PHP_WIN32
} else {
arch = estrndup(fname, fname_len);
arch_len = fname_len;
fname = arch;
phar_unixify_path_separators(arch, arch_len);
#endif
}
if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) {
if (fname == arch && fname != save_fname) {
efree(arch);
fname = save_fname;
}
if (entry) {
efree(entry);
}
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"%s", error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar creation or opening failed");
}
return;
}
if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) {
phar_data->is_zip = 1;
phar_data->is_tar = 0;
}
if (fname == arch) {
efree(arch);
fname = save_fname;
}
if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) {
if (is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"PharData class can only be used for non-executable tar and zip archives");
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar class can only be used for executable tar and zip archives");
}
efree(entry);
return;
}
is_data = phar_data->is_data;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
phar_obj->arc.archive = phar_data;
phar_obj->spl.oth_handler = &phar_spl_foreign_handler;
if (entry) {
fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry);
efree(entry);
} else {
fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname);
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, fname, fname_len, 0);
INIT_PZVAL(&arg2);
ZVAL_LONG(&arg2, flags);
zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj),
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2);
if (!phar_data->is_persistent) {
phar_obj->arc.archive->is_data = is_data;
} else if (!EG(exception)) {
/* register this guy so we can modify if necessary */
zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL);
}
phar_obj->spl.info_class = phar_ce_entry;
efree(fname);
#endif /* HAVE_SPL */
}
/* }}} */
/* {{{ proto array Phar::getSupportedSignatures()
* Return array of supported signature types
*/
PHP_METHOD(Phar, getSupportedSignatures)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_stringl(return_value, "MD5", 3, 1);
add_next_index_stringl(return_value, "SHA-1", 5, 1);
#ifdef PHAR_HASH_OK
add_next_index_stringl(return_value, "SHA-256", 7, 1);
add_next_index_stringl(return_value, "SHA-512", 7, 1);
#endif
#if PHAR_HAVE_OPENSSL
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
#else
if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
}
#endif
}
/* }}} */
/* {{{ proto array Phar::getSupportedCompression()
* Return array of supported comparession algorithms
*/
PHP_METHOD(Phar, getSupportedCompression)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
phar_request_initialize(TSRMLS_C);
if (PHAR_G(has_zlib)) {
add_next_index_stringl(return_value, "GZ", 2, 1);
}
if (PHAR_G(has_bz2)) {
add_next_index_stringl(return_value, "BZIP2", 5, 1);
}
}
/* }}} */
/* {{{ proto array Phar::unlinkArchive(string archive)
* Completely remove a phar archive from memory and disk
*/
PHP_METHOD(Phar, unlinkArchive)
{
char *fname, *error, *zname, *arch, *entry;
int fname_len, zname_len, arch_len, entry_len;
phar_archive_data *phar;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (!fname_len) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"\"");
return;
}
if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\": %s", fname, error);
efree(error);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\"", fname);
}
return;
}
zname = (char*)zend_get_executed_filename(TSRMLS_C);
zname_len = strlen(zname);
if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) {
if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" cannot be unlinked from within itself", fname);
efree(arch);
efree(entry);
return;
}
efree(arch);
efree(entry);
}
if (phar->is_persistent) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname);
return;
}
if (phar->refcount) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname);
return;
}
fname = estrndup(phar->fname, phar->fname_len);
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar_archive_delref(phar TSRMLS_CC);
unlink(fname);
efree(fname);
RETURN_TRUE;
}
/* }}} */
#if HAVE_SPL
#define PHAR_ARCHIVE_OBJECT() \
phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \
if (!phar_obj->arc.archive) { \
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
"Cannot call method on an uninitialized Phar object"); \
return; \
}
/* {{{ proto void Phar::__destruct()
* if persistent, remove from the cache
*/
PHP_METHOD(Phar, __destruct)
{
phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) {
zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive));
}
}
/* }}} */
struct _phar_t {
phar_archive_object *p;
zend_class_entry *c;
char *b;
uint l;
zval *ret;
int count;
php_stream *fp;
};
static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */
{
zval **value;
zend_uchar key_type;
zend_bool close_fp = 1;
ulong int_key;
struct _phar_t *p_obj = (struct _phar_t*) puser;
uint str_key_len, base_len = p_obj->l, fname_len;
phar_entry_data *data;
php_stream *fp;
size_t contents_len;
char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL;
phar_zstr key;
char *str_key;
zend_class_entry *ce = p_obj->c;
phar_archive_object *phar_obj = p_obj->p;
char *str = "[stream]";
iter->funcs->get_current_data(iter, &value TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (!value) {
/* failure in get_current_data */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name);
return ZEND_HASH_APPLY_STOP;
}
switch (Z_TYPE_PP(value)) {
#if PHP_VERSION_ID >= 60000
case IS_UNICODE:
zval_unicode_to_string(*(value) TSRMLS_CC);
/* break intentionally omitted */
#endif
case IS_STRING:
break;
case IS_RESOURCE:
php_stream_from_zval_no_verify(fp, value);
if (!fp) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (iter->funcs->get_current_key) {
key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (key_type == HASH_KEY_IS_LONG) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (key_type > 9) { /* IS_UNICODE == 10 */
#if PHP_VERSION_ID < 60000
/* this can never happen, but fixes a compile warning */
spprintf(&str_key, 0, "%s", key);
#else
spprintf(&str_key, 0, "%v", key);
ezfree(key);
#endif
} else {
PHAR_STR(key, str_key);
}
save = str_key;
if (str_key[str_key_len - 1] == '\0') {
str_key_len--;
}
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
close_fp = 0;
opened = (char *) estrndup(str, sizeof("[stream]") - 1);
goto after_open_fp;
case IS_OBJECT:
if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) {
char *test = NULL;
zval dummy;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC);
if (!base_len) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name);
return ZEND_HASH_APPLY_STOP;
}
switch (intern->type) {
case SPL_FS_DIR:
#if PHP_VERSION_ID >= 60000
test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s;
#elif PHP_VERSION_ID >= 50300
test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC);
#else
test = intern->path;
#endif
fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name);
php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC);
if (Z_BVAL(dummy)) {
/* ignore directories */
efree(fname);
return ZEND_HASH_APPLY_KEEP;
}
test = expand_filepath(fname, NULL TSRMLS_CC);
efree(fname);
if (test) {
fname = test;
fname_len = strlen(fname);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
return ZEND_HASH_APPLY_STOP;
}
save = fname;
goto phar_spl_fileinfo;
case SPL_FS_INFO:
case SPL_FS_FILE:
#if PHP_VERSION_ID >= 60000
if (intern->file_name_type == IS_UNICODE) {
zval zv;
INIT_ZVAL(zv);
Z_UNIVAL(zv) = intern->file_name;
Z_UNILEN(zv) = intern->file_name_len;
Z_TYPE(zv) = IS_UNICODE;
zval_copy_ctor(&zv);
zval_unicode_to_string(&zv TSRMLS_CC);
fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC);
ezfree(Z_UNIVAL(zv));
} else {
fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC);
}
#else
fname = expand_filepath(intern->file_name, NULL TSRMLS_CC);
#endif
if (!fname) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
return ZEND_HASH_APPLY_STOP;
}
fname_len = strlen(fname);
save = fname;
goto phar_spl_fileinfo;
}
}
/* fall-through */
default:
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
fname = Z_STRVAL_PP(value);
fname_len = Z_STRLEN_PP(value);
phar_spl_fileinfo:
if (base_len) {
temp = expand_filepath(base, NULL TSRMLS_CC);
if (!temp) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
if (save) {
efree(save);
}
return ZEND_HASH_APPLY_STOP;
}
base = temp;
base_len = strlen(base);
if (strstr(fname, base)) {
str_key_len = fname_len - base_len;
if (str_key_len <= 0) {
if (save) {
efree(save);
efree(temp);
}
return ZEND_HASH_APPLY_KEEP;
}
str_key = fname + base_len;
if (*str_key == '/' || *str_key == '\\') {
str_key++;
str_key_len--;
}
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base);
if (save) {
efree(save);
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
} else {
if (iter->funcs->get_current_key) {
key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (key_type == HASH_KEY_IS_LONG) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (key_type > 9) { /* IS_UNICODE == 10 */
#if PHP_VERSION_ID < 60000
/* this can never happen, but fixes a compile warning */
spprintf(&str_key, 0, "%s", key);
#else
spprintf(&str_key, 0, "%v", key);
ezfree(key);
#endif
} else {
PHAR_STR(key, str_key);
}
save = str_key;
if (str_key[str_key_len - 1] == '\0') str_key_len--;
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
#endif
if (php_check_open_basedir(fname TSRMLS_CC)) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
/* try to open source file, then create internal phar file and copy contents */
fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened);
if (!fp) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
after_open_fp:
if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) {
/* silently skip any files that would be added to the magic .phar directory */
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
if (opened) {
efree(opened);
}
if (close_fp) {
php_stream_close(fp);
}
return ZEND_HASH_APPLY_KEEP;
}
if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error);
efree(error);
if (save) {
efree(save);
}
if (opened) {
efree(opened);
}
if (temp) {
efree(temp);
}
if (close_fp) {
php_stream_close(fp);
}
return ZEND_HASH_APPLY_STOP;
} else {
if (error) {
efree(error);
}
/* convert to PHAR_UFP */
if (data->internal_file->fp_type == PHAR_MOD) {
php_stream_close(data->internal_file->fp);
}
data->internal_file->fp = NULL;
data->internal_file->fp_type = PHAR_UFP;
data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp);
data->fp = NULL;
phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len);
data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize =
php_stream_tell(p_obj->fp) - data->internal_file->offset;
}
if (close_fp) {
php_stream_close(fp);
}
add_assoc_string(p_obj->ret, str_key, opened, 0);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
phar_entry_delref(data TSRMLS_CC);
return ZEND_HASH_APPLY_KEEP;
}
/* }}} */
/* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex])
* Construct a phar archive from an existing directory, recursively.
* Optional second parameter is a regular expression for filtering directory contents.
*
* Return value is an array mapping phar index to actual files added.
*/
PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
int dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, *iter, *iteriter, *regexiter = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
MAKE_STD_ZVAL(iter);
if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg);
ZVAL_STRINGL(&arg, dir, dir_len, 0);
INIT_PZVAL(&arg2);
#if PHP_VERSION_ID < 50300
ZVAL_LONG(&arg2, 0);
#else
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
#endif
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
MAKE_STD_ZVAL(iteriter);
if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
MAKE_STD_ZVAL(regexiter);
if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(regexiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg2);
ZVAL_STRINGL(&arg2, regex, regex_len, 0);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
/* }}} */
/* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory])
* Construct a phar archive from an iterator. The iterator must return a series of strings
* that are full paths to files that should be added to the phar. The iterator key should
* be the path that the file will have within the phar archive.
*
* If base directory is specified, then the key will be ignored, and instead the portion of
* the current value minus the base directory will be used
*
* Returned is an array mapping phar index to actual file added
*/
PHP_METHOD(Phar, buildFromIterator)
{
zval *obj;
char *error;
uint base_len = 0;
char *base = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
array_init(return_value);
pass.c = Z_OBJCE_P(obj);
pass.p = phar_obj;
pass.b = base;
pass.l = base_len;
pass.ret = return_value;
pass.count = 0;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\": unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
php_stream_close(pass.fp);
}
}
/* }}} */
/* {{{ proto int Phar::count()
* Returns the number of entries in the Phar archive
*/
PHP_METHOD(Phar, count)
{
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest));
}
/* }}} */
/* {{{ proto bool Phar::isFileFormat(int format)
* Returns true if the phar archive is based on the tar/zip/phar file format depending
* on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in
*/
PHP_METHOD(Phar, isFileFormat)
{
long type;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &type) == FAILURE) {
RETURN_FALSE;
}
switch (type) {
case PHAR_FORMAT_TAR:
RETURN_BOOL(phar_obj->arc.archive->is_tar);
case PHAR_FORMAT_ZIP:
RETURN_BOOL(phar_obj->arc.archive->is_zip);
case PHAR_FORMAT_PHAR:
RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip);
default:
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown file format specified");
}
}
/* }}} */
static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) /* {{{ */
{
char *error;
off_t offset;
phar_entry_info *link;
if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) {
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename);
}
return FAILURE;
}
/* copy old contents in entirety */
phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC);
offset = php_stream_tell(fp);
link = phar_get_link_source(entry TSRMLS_CC);
if (!link) {
link = entry;
}
if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename);
return FAILURE;
}
if (entry->fp_type == PHAR_MOD) {
/* save for potential restore on error */
entry->cfp = entry->fp;
entry->fp = NULL;
}
/* set new location of file contents */
entry->fp_type = PHAR_FP;
entry->offset = offset;
return SUCCESS;
}
/* }}} */
static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */
{
const char *oldname = NULL;
char *oldpath = NULL;
char *basename = NULL, *basepath = NULL;
char *newname = NULL, *newpath = NULL;
zval *ret, arg1;
zend_class_entry *ce;
char *error;
const char *pcr_error;
int ext_len = ext ? strlen(ext) : 0;
int oldname_len;
phar_archive_data **pphar = NULL;
php_stream_statbuf ssb;
if (!ext) {
if (phar->is_zip) {
if (phar->is_data) {
ext = "zip";
} else {
ext = "phar.zip";
}
} else if (phar->is_tar) {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
if (phar->is_data) {
ext = "tar.gz";
} else {
ext = "phar.tar.gz";
}
break;
case PHAR_FILE_COMPRESSED_BZ2:
if (phar->is_data) {
ext = "tar.bz2";
} else {
ext = "phar.tar.bz2";
}
break;
default:
if (phar->is_data) {
ext = "tar";
} else {
ext = "phar.tar";
}
}
} else {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
ext = "phar.gz";
break;
case PHAR_FILE_COMPRESSED_BZ2:
ext = "phar.bz2";
break;
default:
ext = "phar";
}
}
} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
if (phar->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
}
return NULL;
}
if (ext[0] == '.') {
++ext;
}
oldpath = estrndup(phar->fname, phar->fname_len);
oldname = zend_memrchr(phar->fname, '/', phar->fname_len);
++oldname;
oldname_len = strlen(oldname);
basename = estrndup(oldname, oldname_len);
spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext);
efree(basename);
basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
phar->fname = newpath;
phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
efree(basepath);
efree(newname);
if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname);
return NULL;
}
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {
if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {
if (!zend_hash_num_elements(&phar->manifest)) {
(*pphar)->is_tar = phar->is_tar;
(*pphar)->is_zip = phar->is_zip;
(*pphar)->is_data = phar->is_data;
(*pphar)->flags = phar->flags;
(*pphar)->fp = phar->fp;
phar->fp = NULL;
phar_destroy_phar_data(phar TSRMLS_CC);
phar = *pphar;
phar->refcount++;
newpath = oldpath;
goto its_ok;
}
}
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname);
return NULL;
}
its_ok:
if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
efree(oldpath);
return NULL;
}
if (!phar->is_data) {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
if (phar->alias) {
if (phar->is_temporary_alias) {
phar->alias = NULL;
phar->alias_len = 0;
} else {
phar->alias = estrndup(newpath, strlen(newpath));
phar->alias_len = strlen(newpath);
phar->is_temporary_alias = 1;
zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);
}
}
} else {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
phar->alias = NULL;
phar->alias_len = 0;
}
if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
return NULL;
}
phar_flush(phar, 0, 0, 1, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
efree(error);
efree(oldpath);
return NULL;
}
efree(oldpath);
if (phar->is_data) {
ce = phar_ce_data;
} else {
ce = phar_ce_archive;
}
MAKE_STD_ZVAL(ret);
if (SUCCESS != object_init_ex(ret, ce)) {
zval_dtor(ret);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
return NULL;
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);
zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1);
return ret;
}
/* }}} */
static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar;
phar_entry_info *entry, newentry;
zval *ret;
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data));
/* set whole-archive compression and type from parameter */
phar->flags = flags;
phar->is_data = source->is_data;
switch (convert) {
case PHAR_FORMAT_TAR:
phar->is_tar = 1;
break;
case PHAR_FORMAT_ZIP:
phar->is_zip = 1;
break;
default:
phar->is_data = 0;
break;
}
zend_hash_init(&(phar->manifest), sizeof(phar_entry_info),
zend_get_hash_value, destroy_phar_manifest_entry, 0);
zend_hash_init(&phar->mounted_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
zend_hash_init(&phar->virtual_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
phar->fp = php_stream_fopen_tmpfile();
if (phar->fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to create temporary file");
return NULL;
}
phar->fname = source->fname;
phar->fname_len = source->fname_len;
phar->is_temporary_alias = source->is_temporary_alias;
phar->alias = source->alias;
if (source->metadata) {
zval *t;
t = source->metadata;
ALLOC_ZVAL(phar->metadata);
*phar->metadata = *t;
zval_copy_ctor(phar->metadata);
#if PHP_VERSION_ID < 50300
phar->metadata->refcount = 1;
#else
Z_SET_REFCOUNT_P(phar->metadata, 1);
#endif
phar->metadata_len = 0;
}
/* first copy each file's uncompressed contents to a temporary file and set per-file flags */
for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) {
if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) {
zend_hash_destroy(&(phar->manifest));
php_stream_close(phar->fp);
efree(phar);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\"", source->fname);
return NULL;
}
newentry = *entry;
if (newentry.link) {
newentry.link = estrdup(newentry.link);
goto no_copy;
}
if (newentry.tmp) {
newentry.tmp = estrdup(newentry.tmp);
goto no_copy;
}
newentry.metadata_str.c = 0;
if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) {
zend_hash_destroy(&(phar->manifest));
php_stream_close(phar->fp);
efree(phar);
/* exception already thrown */
return NULL;
}
no_copy:
newentry.filename = estrndup(newentry.filename, newentry.filename_len);
if (newentry.metadata) {
zval *t;
t = newentry.metadata;
ALLOC_ZVAL(newentry.metadata);
*newentry.metadata = *t;
zval_copy_ctor(newentry.metadata);
#if PHP_VERSION_ID < 50300
newentry.metadata->refcount = 1;
#else
Z_SET_REFCOUNT_P(newentry.metadata, 1);
#endif
newentry.metadata_str.c = NULL;
newentry.metadata_str.len = 0;
}
newentry.is_zip = phar->is_zip;
newentry.is_tar = phar->is_tar;
if (newentry.is_tar) {
newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE);
}
newentry.is_modified = 1;
newentry.phar = phar;
newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */
phar_set_inode(&newentry TSRMLS_CC);
zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL);
phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC);
}
if ((ret = phar_rename_archive(phar, ext, 0 TSRMLS_CC))) {
return ret;
} else {
zend_hash_destroy(&(phar->manifest));
zend_hash_destroy(&(phar->mounted_dirs));
zend_hash_destroy(&(phar->virtual_dirs));
php_stream_close(phar->fp);
efree(phar->fname);
efree(phar);
return NULL;
/* }}} */
|
CWE-20
| 178,462 | 10,431 |
269655417478932022718928812786561571401
| null | null | null |
php
|
2cc4e69cc6d8dbc4b3568ad3dd583324a7c11d64
| 1 |
PHP_FUNCTION(pg_get_notify)
{
zval *pgsql_link;
int id = -1;
long result_type = PGSQL_ASSOC;
PGconn *pgsql;
PGnotify *pgsql_notify;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l",
&pgsql_link, &result_type) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (!(result_type & PGSQL_BOTH)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
RETURN_FALSE;
}
PQconsumeInput(pgsql);
pgsql_notify = PQnotifies(pgsql);
if (!pgsql_notify) {
/* no notify message */
RETURN_FALSE;
}
array_init(return_value);
if (result_type & PGSQL_NUM) {
add_index_string(return_value, 0, pgsql_notify->relname, 1);
add_index_long(return_value, 1, pgsql_notify->be_pid);
#if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) {
#else
if (atof(PG_VERSION) >= 9.0) {
#endif
#if HAVE_PQPARAMETERSTATUS
add_index_string(return_value, 2, pgsql_notify->extra, 1);
#endif
}
}
if (result_type & PGSQL_ASSOC) {
add_assoc_string(return_value, "message", pgsql_notify->relname, 1);
add_assoc_long(return_value, "pid", pgsql_notify->be_pid);
#if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) {
#else
if (atof(PG_VERSION) >= 9.0) {
#endif
#if HAVE_PQPARAMETERSTATUS
add_assoc_string(return_value, "payload", pgsql_notify->extra, 1);
#endif
}
}
PQfreemem(pgsql_notify);
}
/* }}} */
/* {{{ proto int pg_get_pid([resource connection)
Get backend(server) pid */
PHP_FUNCTION(pg_get_pid)
{
zval *pgsql_link;
int id = -1;
PGconn *pgsql;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
&pgsql_link) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
RETURN_LONG(PQbackendPID(pgsql));
}
/* }}} */
/* {{{ php_pgsql_meta_data
* TODO: Add meta_data cache for better performance
*/
PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, zval *meta TSRMLS_DC)
{
PGresult *pg_result;
char *src, *tmp_name, *tmp_name2 = NULL;
char *escaped;
smart_str querystr = {0};
size_t new_len;
int i, num_rows;
zval *elem;
if (!*table_name) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The table name must be specified");
return FAILURE;
}
src = estrdup(table_name);
tmp_name = php_strtok_r(src, ".", &tmp_name2);
if (!tmp_name2 || !*tmp_name2) {
/* Default schema */
tmp_name2 = tmp_name;
"SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotnull, a.atthasdef, a.attndims, t.typtype = 'e' "
"FROM pg_class as c, pg_attribute a, pg_type t, pg_namespace n "
"WHERE a.attnum > 0 AND a.attrelid = c.oid AND c.relname = '");
escaped = (char *)safe_emalloc(strlen(tmp_name2), 2, 1);
new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), NULL);
if (new_len) {
smart_str_appendl(&querystr, escaped, new_len);
}
efree(escaped);
smart_str_appends(&querystr, "' AND c.relnamespace = n.oid AND n.nspname = '");
escaped = (char *)safe_emalloc(strlen(tmp_name), 2, 1);
new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), NULL);
if (new_len) {
smart_str_appendl(&querystr, escaped, new_len);
}
efree(escaped);
smart_str_appends(&querystr, "' AND a.atttypid = t.oid ORDER BY a.attnum;");
smart_str_0(&querystr);
efree(src);
pg_result = PQexec(pg_link, querystr.c);
if (PQresultStatus(pg_result) != PGRES_TUPLES_OK || (num_rows = PQntuples(pg_result)) == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Table '%s' doesn't exists", table_name);
smart_str_free(&querystr);
PQclear(pg_result);
return FAILURE;
}
smart_str_free(&querystr);
for (i = 0; i < num_rows; i++) {
char *name;
MAKE_STD_ZVAL(elem);
array_init(elem);
add_assoc_long(elem, "num", atoi(PQgetvalue(pg_result,i,1)));
add_assoc_string(elem, "type", PQgetvalue(pg_result,i,2), 1);
add_assoc_long(elem, "len", atoi(PQgetvalue(pg_result,i,3)));
if (!strcmp(PQgetvalue(pg_result,i,4), "t")) {
add_assoc_bool(elem, "not null", 1);
}
else {
add_assoc_bool(elem, "not null", 0);
}
if (!strcmp(PQgetvalue(pg_result,i,5), "t")) {
add_assoc_bool(elem, "has default", 1);
}
else {
add_assoc_bool(elem, "has default", 0);
}
add_assoc_long(elem, "array dims", atoi(PQgetvalue(pg_result,i,6)));
if (!strcmp(PQgetvalue(pg_result,i,7), "t")) {
add_assoc_bool(elem, "is enum", 1);
}
else {
add_assoc_bool(elem, "is enum", 0);
}
name = PQgetvalue(pg_result,i,0);
add_assoc_zval(meta, name, elem);
}
PQclear(pg_result);
return SUCCESS;
}
/* }}} */
| 178,472 | 10,439 |
860125863243371090281050481916621641
| null | null | null |
|
php
|
0765623d6991b62ffcd93ddb6be8a5203a2fa7e2
| 1 |
ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC)
{
php_stream *tmpstream = NULL;
databuf_t *data = NULL;
char *ptr;
int ch, lastch;
size_t size, rcvd;
size_t lines;
char **ret = NULL;
char **entry;
char *text;
if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory.");
return NULL;
}
if (!ftp_type(ftp, FTPTYPE_ASCII)) {
goto bail;
}
if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) {
goto bail;
}
ftp->data = data;
if (!ftp_putcmd(ftp, cmd, path)) {
goto bail;
}
if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) {
goto bail;
}
/* some servers don't open a ftp-data connection if the directory is empty */
if (ftp->resp == 226) {
ftp->data = data_close(ftp, data);
php_stream_close(tmpstream);
return ecalloc(1, sizeof(char*));
}
/* pull data buffer into tmpfile */
if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) {
goto bail;
}
size = 0;
lines = 0;
lastch = 0;
while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) {
if (rcvd == -1 || rcvd > ((size_t)(-1))-size) {
goto bail;
}
php_stream_write(tmpstream, data->buf, rcvd);
size += rcvd;
for (ptr = data->buf; rcvd; rcvd--, ptr++) {
if (*ptr == '\n' && lastch == '\r') {
lines++;
} else {
size++;
}
lastch = *ptr;
}
lastch = *ptr;
}
}
|
CWE-119
| 178,473 | 10,440 |
335438984272943789174703422191509674630
| null | null | null |
php
|
d2ac264ffea5ca2e85640b6736e0c7cd4ee9a4a9
| 1 |
PHPAPI char *php_escape_shell_arg(char *str)
{
int x, y = 0, l = strlen(str);
char *cmd;
size_t estimate = (4 * l) + 3;
TSRMLS_FETCH();
cmd = safe_emalloc(4, l, 3); /* worst case */
#ifdef PHP_WIN32
cmd[y++] = '"';
#else
cmd[y++] = '\'';
#endif
for (x = 0; x < l; x++) {
int mb_len = php_mblen(str + x, (l - x));
/* skip non-valid multibyte characters */
if (mb_len < 0) {
continue;
} else if (mb_len > 1) {
memcpy(cmd + y, str + x, mb_len);
y += mb_len;
x += mb_len - 1;
continue;
}
switch (str[x]) {
#ifdef PHP_WIN32
case '"':
case '%':
cmd[y++] = ' ';
break;
#else
case '\'':
cmd[y++] = '\'';
cmd[y++] = '\\';
cmd[y++] = '\'';
#endif
/* fall-through */
default:
cmd[y++] = str[x];
}
}
#ifdef PHP_WIN32
cmd[y++] = '"';
#else
cmd[y++] = '\'';
return cmd;
}
|
CWE-78
| 178,474 | 10,441 |
201437012404707318561768240174493294327
| null | null | null |
php
|
fb83c76deec58f1fab17c350f04c9f042e5977d1
| 1 |
PHPAPI char *php_lookup_class_name(zval *object, zend_uint *nlen)
{
zval **val;
char *retval = NULL;
HashTable *object_properties;
TSRMLS_FETCH();
object_properties = Z_OBJPROP_P(object);
if (zend_hash_find(object_properties, MAGIC_MEMBER, sizeof(MAGIC_MEMBER), (void **) &val) == SUCCESS) {
retval = estrndup(Z_STRVAL_PP(val), Z_STRLEN_PP(val));
if (nlen) {
*nlen = Z_STRLEN_PP(val);
}
}
return retval;
}
| 178,475 | 10,442 |
187977021874060054824676909058691460397
| null | null | null |
|
php
|
1cbd25ca15383394ffa9ee8601c5de4c0f2f90e1
| 1 |
static void spl_ptr_heap_insert(spl_ptr_heap *heap, spl_ptr_heap_element elem, void *cmp_userdata TSRMLS_DC) { /* {{{ */
int i;
if (heap->count+1 > heap->max_size) {
/* we need to allocate more memory */
heap->elements = (void **) safe_erealloc(heap->elements, sizeof(spl_ptr_heap_element), (heap->max_size), (sizeof(spl_ptr_heap_element) * (heap->max_size)));
heap->max_size *= 2;
}
heap->ctor(elem TSRMLS_CC);
/* sifting up */
for(i = heap->count++; i > 0 && heap->cmp(heap->elements[(i-1)/2], elem, cmp_userdata TSRMLS_CC) < 0; i = (i-1)/2) {
heap->elements[i] = heap->elements[(i-1)/2];
}
if (EG(exception)) {
/* exception thrown during comparison */
}
heap->elements[i] = elem;
}
/* }}} */
| 178,479 | 10,446 |
155245803379738251097763028206886086531
| null | null | null |
|
qemu
|
4b53c2c72cb5541cf394033b528a6fe2a86c0ac1
| 1 |
int virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
uint32_t num;
uint32_t features;
uint32_t supported_features;
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
if (num > VIRTIO_PCI_QUEUE_MAX) {
error_report("Invalid number of PCI queues: 0x%x", num);
return -1;
}
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
|
CWE-94
| 178,508 | 10,459 |
324234853826218238386048386597987092822
| null | null | null |
pixman
|
857e40f3d2bc2cfb714913e0cd7e6184cf69aca3
| 1 |
create_bits (pixman_format_code_t format,
int width,
int height,
int * rowstride_bytes,
pixman_bool_t clear)
{
int stride;
size_t buf_size;
int bpp;
/* what follows is a long-winded way, avoiding any possibility of integer
* overflows, of saying:
* stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t);
*/
bpp = PIXMAN_FORMAT_BPP (format);
if (_pixman_multiply_overflows_int (width, bpp))
return NULL;
stride = width * bpp;
if (_pixman_addition_overflows_int (stride, 0x1f))
return NULL;
stride += 0x1f;
stride >>= 5;
stride *= sizeof (uint32_t);
if (_pixman_multiply_overflows_size (height, stride))
return NULL;
buf_size = height * stride;
if (rowstride_bytes)
*rowstride_bytes = stride;
if (clear)
return calloc (buf_size, 1);
else
return malloc (buf_size);
}
|
CWE-189
| 178,509 | 10,460 |
338189852796356454617405235087008423240
| null | null | null |
qemu
|
3c99afc779c2c78718a565ad8c5e98de7c2c7484
| 1 |
static int vmxnet3_post_load(void *opaque, int version_id)
{
VMXNET3State *s = opaque;
PCIDevice *d = PCI_DEVICE(s);
vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);
vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);
if (s->msix_used) {
if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) {
VMW_WRPRN("Failed to re-use MSI-X vectors");
msix_uninit(d, &s->msix_bar, &s->msix_bar);
s->msix_used = false;
return -1;
}
}
return 0;
}
|
CWE-20
| 178,526 | 10,461 |
41449705420556697902463716672708454199
| null | null | null |
qemu
|
d2ef4b61fe6d33d2a5dcf100a9b9440de341ad62
| 1 |
static int get_int32_le(QEMUFile *f, void *pv, size_t size)
{
int32_t loaded;
int32_t loaded;
qemu_get_sbe32s(f, &loaded);
if (loaded <= *cur) {
*cur = loaded;
return 0;
}
}
|
CWE-119
| 178,531 | 10,462 |
134727717376042796464641496758190048357
| null | null | null |
exempi
|
886cd1d2314755adb1f4cdb99c16ff00830f0331
| 1 |
bool TradQT_Manager::ParseCachedBoxes ( const MOOV_Manager & moovMgr )
{
MOOV_Manager::BoxInfo udtaInfo;
MOOV_Manager::BoxRef udtaRef = moovMgr.GetBox ( "moov/udta", &udtaInfo );
if ( udtaRef == 0 ) return false;
for ( XMP_Uns32 i = 0; i < udtaInfo.childCount; ++i ) {
MOOV_Manager::BoxInfo currInfo;
MOOV_Manager::BoxRef currRef = moovMgr.GetNthChild ( udtaRef, i, &currInfo );
if ( currRef == 0 ) break; // Sanity check, should not happen.
if ( (currInfo.boxType >> 24) != 0xA9 ) continue;
if ( currInfo.contentSize < 2+2+1 ) continue; // Want enough for a non-empty value.
InfoMapPos newInfo = this->parsedBoxes.insert ( this->parsedBoxes.end(),
InfoMap::value_type ( currInfo.boxType, ParsedBoxInfo ( currInfo.boxType ) ) );
std::vector<ValueInfo> * newValues = &newInfo->second.values;
XMP_Uns8 * boxPtr = (XMP_Uns8*) currInfo.content;
XMP_Uns8 * boxEnd = boxPtr + currInfo.contentSize;
XMP_Uns16 miniLen, macLang;
for ( ; boxPtr < boxEnd-4; boxPtr += miniLen ) {
miniLen = 4 + GetUns16BE ( boxPtr ); // ! Include header in local miniLen.
macLang = GetUns16BE ( boxPtr+2);
if ( (miniLen <= 4) || (miniLen > (boxEnd - boxPtr)) ) continue; // Ignore bad or empty values.
XMP_StringPtr valuePtr = (char*)(boxPtr+4);
size_t valueLen = miniLen - 4;
newValues->push_back ( ValueInfo() );
ValueInfo * newValue = &newValues->back();
newValue->macLang = macLang;
if ( IsMacLangKnown ( macLang ) ) newValue->xmpLang = GetXMPLang ( macLang );
newValue->macValue.assign ( valuePtr, valueLen );
}
}
return (! this->parsedBoxes.empty());
} // TradQT_Manager::ParseCachedBoxes
|
CWE-835
| 178,536 | 10,463 |
23259527281897319442452234034874581404
| null | null | null |
exempi
|
65a8492832b7335ffabd01f5f64d89dec757c260
| 1 |
Chunk::Chunk( ContainerChunk* parent, RIFF_MetaHandler* handler, bool skip, ChunkType c )
{
chunkType = c; // base class assumption
this->parent = parent;
this->oldSize = 0;
this->hasChange = false; // [2414649] valid assumption at creation time
XMP_IO* file = handler->parent->ioRef;
this->oldPos = file->Offset();
this->id = XIO::ReadUns32_LE( file );
this->oldSize = XIO::ReadUns32_LE( file ) + 8;
XMP_Int64 chunkEnd = this->oldPos + this->oldSize;
if ( parent != 0 ) chunkLimit = parent->oldPos + parent->oldSize;
if ( chunkEnd > chunkLimit ) {
bool isUpdate = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenForUpdate );
bool repairFile = XMP_OptionIsSet ( handler->parent->openFlags, kXMPFiles_OpenRepairFile );
if ( (! isUpdate) || (repairFile && (parent == 0)) ) {
this->oldSize = chunkLimit - this->oldPos;
} else {
XMP_Throw ( "Bad RIFF chunk size", kXMPErr_BadFileFormat );
}
}
this->newSize = this->oldSize;
this->needSizeFix = false;
if ( skip ) file->Seek ( (this->oldSize - 8), kXMP_SeekFromCurrent );
if ( this->parent != NULL )
{
this->parent->children.push_back( this );
if( this->chunkType == chunk_VALUE )
this->parent->childmap.insert( std::make_pair( this->id, (ValueChunk*) this ) );
}
}
|
CWE-190
| 178,541 | 10,468 |
327787765077432342719030178938099860546
| null | null | null |
qemu
|
f153b563f8cf121aebf5a2fff5f0110faf58ccb3
| 1 |
static void cirrus_invalidate_region(CirrusVGAState * s, int off_begin,
int off_pitch, int bytesperline,
int lines)
{
int y;
int off_cur;
int off_cur_end;
for (y = 0; y < lines; y++) {
off_cur = off_begin;
off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask;
memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur);
off_begin += off_pitch;
}
uint8_t *dst;
dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask);
if (blit_is_unsafe(s, false))
return 0;
(*s->cirrus_rop) (s, dst, src,
s->cirrus_blt_dstpitch, 0,
s->cirrus_blt_width, s->cirrus_blt_height);
cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,
s->cirrus_blt_dstpitch, s->cirrus_blt_width,
s->cirrus_blt_height);
return 1;
}
|
CWE-125
| 178,560 | 10,469 |
18925896616992008774181617923997847101
| null | null | null |
qemu
|
c05e4667be91b46ab42b5a11babf8e84d476cc6b
| 1 |
int qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
new_l1_bytes = s->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
ret = bdrv_pread(bs->file, sn->l1_table_offset, new_l1_table, new_l1_bytes);
if (ret < 0) {
error_setg(errp, "Failed to read l1 table for snapshot");
g_free(new_l1_table);
return ret;
}
/* Switch the L1 table */
g_free(s->l1_table);
s->l1_size = sn->l1_size;
s->l1_table_offset = sn->l1_table_offset;
s->l1_table = new_l1_table;
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
}
return 0;
}
|
CWE-119
| 178,574 | 10,470 |
144482353548212763788796691478083703453
| null | null | null |
qemu
|
509a41bab5306181044b5fff02eadf96d9c8676a
| 1 |
static int cloop_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVCloopState *s = bs->opaque;
uint32_t offsets_size, max_compressed_block_size = 1, i;
int ret;
bs->read_only = 1;
/* read header */
ret = bdrv_pread(bs->file, 128, &s->block_size, 4);
if (ret < 0) {
return ret;
}
s->block_size = be32_to_cpu(s->block_size);
if (s->block_size % 512) {
error_setg(errp, "block_size %u must be a multiple of 512",
s->block_size);
return -EINVAL;
}
if (s->block_size == 0) {
error_setg(errp, "block_size cannot be zero");
return -EINVAL;
}
/* cloop's create_compressed_fs.c warns about block sizes beyond 256 KB but
* we can accept more. Prevent ridiculous values like 4 GB - 1 since we
* need a buffer this big.
*/
if (s->block_size > MAX_BLOCK_SIZE) {
error_setg(errp, "block_size %u must be %u MB or less",
s->block_size,
MAX_BLOCK_SIZE / (1024 * 1024));
return -EINVAL;
}
ret = bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4);
if (ret < 0) {
return ret;
}
s->n_blocks = be32_to_cpu(s->n_blocks);
/* read offsets */
offsets_size = s->n_blocks * sizeof(uint64_t);
s->offsets = g_malloc(offsets_size);
if (i > 0) {
uint32_t size = s->offsets[i] - s->offsets[i - 1];
if (size > max_compressed_block_size) {
max_compressed_block_size = size;
}
}
}
|
CWE-190
| 178,575 | 10,471 |
202962117817616132422794339638756980464
| null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.