uint16 BNEP_DISCONNECT_REQ_T_PDU::get_id() const
{
    return get_uint16 ( BNEP_DISCONNECT_REQ_T_id );
}
Beispiel #2
0
uint16_t gme_game_get_bonus_rounds(const struct gme_game* g) {
  assert(g->type==6);
  return get_uint16(g->raw);
}
Beispiel #3
0
uint16_t gme_game_get_pre_last_round_count(const struct gme_game* g) {
  return get_uint16(gme_game_get_last_round_p(g));
}
Beispiel #4
0
/* Given a path to a Zip file and a toc_entry, return the (uncompressed)
   data as a new reference. */
static PyObject *
get_data(PyObject *archive, PyObject *toc_entry)
{
    PyObject *raw_data = NULL, *data, *decompress;
    char *buf;
    FILE *fp;
    PyObject *datapath;
    unsigned short compress, time, date;
    unsigned int crc;
    Py_ssize_t data_size, file_size, bytes_size;
    long file_offset, header_size;
    unsigned char buffer[30];
    const char *errmsg = NULL;

    if (!PyArg_ParseTuple(toc_entry, "OHnnlHHI", &datapath, &compress,
                          &data_size, &file_size, &file_offset, &time,
                          &date, &crc)) {
        return NULL;
    }
    if (data_size < 0) {
        PyErr_Format(ZipImportError, "negative data size");
        return NULL;
    }

    fp = _Py_fopen_obj(archive, "rb");
    if (!fp) {
        return NULL;
    }
    /* Check to make sure the local file header is correct */
    if (fseek(fp, file_offset, 0) == -1) {
        goto file_error;
    }
    if (fread(buffer, 1, 30, fp) != 30) {
        goto eof_error;
    }
    if (get_uint32(buffer) != 0x04034B50u) {
        /* Bad: Local File Header */
        errmsg = "bad local file header";
        goto invalid_header;
    }

    header_size = (unsigned int)30 +
        get_uint16(buffer + 26) /* file name */ +
        get_uint16(buffer + 28) /* extra field */;
    if (file_offset > LONG_MAX - header_size) {
        errmsg = "bad local file header size";
        goto invalid_header;
    }
    file_offset += header_size;  /* Start of file data */

    if (data_size > LONG_MAX - 1) {
        fclose(fp);
        PyErr_NoMemory();
        return NULL;
    }
    bytes_size = compress == 0 ? data_size : data_size + 1;
    if (bytes_size == 0) {
        bytes_size++;
    }
    raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size);
    if (raw_data == NULL) {
        goto error;
    }
    buf = PyBytes_AsString(raw_data);

    if (fseek(fp, file_offset, 0) == -1) {
        goto file_error;
    }
    if (fread(buf, 1, data_size, fp) != (size_t)data_size) {
        PyErr_SetString(PyExc_IOError,
                        "zipimport: can't read data");
        goto error;
    }

    fclose(fp);
    fp = NULL;

    if (compress != 0) {
        buf[data_size] = 'Z';  /* saw this in zipfile.py */
        data_size++;
    }
    buf[data_size] = '\0';

    if (compress == 0) {  /* data is not compressed */
        data = PyBytes_FromStringAndSize(buf, data_size);
        Py_DECREF(raw_data);
        return data;
    }

    /* Decompress with zlib */
    decompress = get_decompress_func();
    if (decompress == NULL) {
        PyErr_SetString(ZipImportError,
                        "can't decompress data; "
                        "zlib not available");
        goto error;
    }
    data = PyObject_CallFunction(decompress, "Oi", raw_data, -15);
    Py_DECREF(decompress);
    Py_DECREF(raw_data);
    return data;

eof_error:
    set_file_error(archive, !ferror(fp));
    goto error;

file_error:
    PyErr_Format(ZipImportError, "can't read Zip file: %R", archive);
    goto error;

invalid_header:
    assert(errmsg != NULL);
    PyErr_Format(ZipImportError, "%s: %R", errmsg, archive);
    goto error;

error:
    if (fp != NULL) {
        fclose(fp);
    }
    Py_XDECREF(raw_data);
    return NULL;
}
Beispiel #5
0
/** Respond to an ESTABLISH_INTRO cell by checking the signed data and
 * setting the circuit's purpose and service pk digest.
 */
int
rend_mid_establish_intro(or_circuit_t *circ, const uint8_t *request,
                         size_t request_len)
{
  crypto_pk_t *pk = NULL;
  char buf[DIGEST_LEN+9];
  char expected_digest[DIGEST_LEN];
  char pk_digest[DIGEST_LEN];
  size_t asn1len;
  or_circuit_t *c;
  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  int reason = END_CIRC_REASON_INTERNAL;

  log_info(LD_REND,
           "Received an ESTABLISH_INTRO request on circuit %u",
           (unsigned) circ->p_circ_id);

  if (circ->base_.purpose != CIRCUIT_PURPOSE_OR || circ->base_.n_chan) {
    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
         "Rejecting ESTABLISH_INTRO on non-OR or non-edge circuit.");
    reason = END_CIRC_REASON_TORPROTOCOL;
    goto err;
  }
  if (request_len < 2+DIGEST_LEN)
    goto truncated;
  /* First 2 bytes: length of asn1-encoded key. */
  asn1len = ntohs(get_uint16(request));

  /* Next asn1len bytes: asn1-encoded key. */
  if (request_len < 2+DIGEST_LEN+asn1len)
    goto truncated;
  pk = crypto_pk_asn1_decode((char*)(request+2), asn1len);
  if (!pk) {
    reason = END_CIRC_REASON_TORPROTOCOL;
    log_warn(LD_PROTOCOL, "Couldn't decode public key.");
    goto err;
  }

  /* Next 20 bytes: Hash of rend_circ_nonce | "INTRODUCE" */
  memcpy(buf, circ->rend_circ_nonce, DIGEST_LEN);
  memcpy(buf+DIGEST_LEN, "INTRODUCE", 9);
  if (crypto_digest(expected_digest, buf, DIGEST_LEN+9) < 0) {
    log_warn(LD_BUG, "Internal error computing digest.");
    goto err;
  }
  if (tor_memneq(expected_digest, request+2+asn1len, DIGEST_LEN)) {
    log_warn(LD_PROTOCOL, "Hash of session info was not as expected.");
    reason = END_CIRC_REASON_TORPROTOCOL;
    goto err;
  }
  /* Rest of body: signature of previous data */
  note_crypto_pk_op(REND_MID);
  if (crypto_pk_public_checksig_digest(pk,
                                       (char*)request, 2+asn1len+DIGEST_LEN,
                                       (char*)(request+2+DIGEST_LEN+asn1len),
                                       request_len-(2+DIGEST_LEN+asn1len))<0) {
    log_warn(LD_PROTOCOL,
             "Incorrect signature on ESTABLISH_INTRO cell; rejecting.");
    reason = END_CIRC_REASON_TORPROTOCOL;
    goto err;
  }

  /* The request is valid.  First, compute the hash of Bob's PK.*/
  if (crypto_pk_get_digest(pk, pk_digest)<0) {
    log_warn(LD_BUG, "Internal error: couldn't hash public key.");
    goto err;
  }

  crypto_pk_free(pk); /* don't need it anymore */
  pk = NULL; /* so we don't free it again if err */

  base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
                pk_digest, REND_SERVICE_ID_LEN);

  /* Close any other intro circuits with the same pk. */
  c = NULL;
  while ((c = circuit_get_intro_point((const uint8_t *)pk_digest))) {
    log_info(LD_REND, "Replacing old circuit for service %s",
             safe_str(serviceid));
    circuit_mark_for_close(TO_CIRCUIT(c), END_CIRC_REASON_FINISHED);
    /* Now it's marked, and it won't be returned next time. */
  }

  /* Acknowledge the request. */
  if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
                                   RELAY_COMMAND_INTRO_ESTABLISHED,
                                   "", 0, NULL)<0) {
    log_info(LD_GENERAL, "Couldn't send INTRO_ESTABLISHED cell.");
    goto err;
  }

  /* Now, set up this circuit. */
  circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_INTRO_POINT);
  circuit_set_intro_point_digest(circ, (uint8_t *)pk_digest);

  log_info(LD_REND,
           "Established introduction point on circuit %u for service %s",
           (unsigned) circ->p_circ_id, safe_str(serviceid));

  return 0;
 truncated:
  log_warn(LD_PROTOCOL, "Rejecting truncated ESTABLISH_INTRO cell.");
  reason = END_CIRC_REASON_TORPROTOCOL;
 err:
  if (pk) crypto_pk_free(pk);
  circuit_mark_for_close(TO_CIRCUIT(circ), reason);
  return -1;
}
Beispiel #6
0
/*
 * handling to receive Notification payload
 */
static int
isakmp_info_recv_n(struct ph1handle *iph1, rc_vchar_t *msg)
{
	struct isakmp_pl_n *n = NULL;
	unsigned int type;
	rc_vchar_t *pbuf;
	struct isakmp_parse_t *pa, *pap;
	char *spi;

	if (!(pbuf = isakmp_parse(msg)))
		return -1;
	pa = (struct isakmp_parse_t *)pbuf->v;
	for (pap = pa; pap->type; pap++) {
		switch (pap->type) {
		case ISAKMP_NPTYPE_HASH:
			/* do something here */
			break;
		case ISAKMP_NPTYPE_NONCE:
			/* send to ack */
			break;
		case ISAKMP_NPTYPE_N:
			n = (struct isakmp_pl_n *)pap->ptr;
			break;
		default:
			rc_vfree(pbuf);
			return -1;
		}
	}
	rc_vfree(pbuf);
	if (!n)
		return -1;

	type = get_uint16(&n->type);

	switch (type) {
	case ISAKMP_NTYPE_CONNECTED:
	case ISAKMP_NTYPE_RESPONDER_LIFETIME:
	case ISAKMP_NTYPE_REPLAY_STATUS:
		/* do something */
		break;
	case ISAKMP_NTYPE_INITIAL_CONTACT:
		info_recv_initialcontact(iph1);
		break;
	case ISAKMP_NTYPE_R_U_THERE:
		isakmp_info_recv_r_u(iph1, (struct isakmp_pl_ru *)n,
				     ((struct isakmp *)msg->v)->msgid);
		break;
	case ISAKMP_NTYPE_R_U_THERE_ACK:
		isakmp_info_recv_r_u_ack(iph1, (struct isakmp_pl_ru *)n,
					 ((struct isakmp *)msg->v)->msgid);
		break;

	default:
	    {
		uint32_t msgid = ((struct isakmp *)msg->v)->msgid;
		struct ph2handle *iph2;

		/* XXX there is a potential of dos attack. */
		if (msgid == 0) {
			/* delete ph1 */
			plog(PLOG_PROTOERR, PLOGLOC, 0,
				"delete phase1 handle.\n");
			return -1;
		} else {
			iph2 = getph2bymsgid(iph1, msgid);
			if (iph2 == NULL) {
				plog(PLOG_PROTOERR, PLOGLOC, 0,
					"unknown notify message, "
					"no phase2 handle found.\n");
			} else {
				/* delete ph2 */
				unbindph12(iph2);
				remph2(iph2);
				delph2(iph2);
			}
		}
	    }
		break;
	}

	/* get spi and allocate */
	if (get_uint16(&n->h.len) < sizeof(*n) + n->spi_size) {
		plog(PLOG_PROTOERR, PLOGLOC, 0,
			"invalid spi_size in notification payload.\n");
		return -1;
	}
	spi = val2str((char *)(n + 1), n->spi_size);

	plog(PLOG_DEBUG, PLOGLOC, 0,
		"notification message %d:%s, "
		"doi=%d proto_id=%d spi=%s(size=%d).\n",
		type, s_isakmp_notify_msg(type),
		get_uint32(&n->doi), n->proto_id, spi, n->spi_size);

	racoon_free(spi);

	return(0);
}
Beispiel #7
0
void xs::pgm_receiver_t::in_event (fd_t fd_)
{
    // Read data from the underlying pgm_socket.
    unsigned char *data = NULL;
    const pgm_tsi_t *tsi = NULL;

    if (pending_bytes > 0)
        return;

    if (rx_timer) {
        rm_timer (rx_timer);
        rx_timer = NULL;
    }

    //  TODO: This loop can effectively block other engines in the same I/O
    //  thread in the case of high load.
    while (true) {

        //  Get new batch of data.
        //  Note the workaround made not to break strict-aliasing rules.
        void *tmp = NULL;
        ssize_t received = pgm_socket.receive (&tmp, &tsi);
        data = (unsigned char*) tmp;

        //  No data to process. This may happen if the packet received is
        //  neither ODATA nor ODATA.
        if (received == 0) {
            if (errno == ENOMEM || errno == EBUSY) {
                const long timeout = pgm_socket.get_rx_timeout ();
                xs_assert (!rx_timer);
                rx_timer = add_timer (timeout);
            }
            break;
        }

        //  Find the peer based on its TSI.
        peers_t::iterator it = peers.find (*tsi);

        //  Data loss. Delete decoder and mark the peer as disjoint.
        if (received == -1) {
            if (it != peers.end ()) {
                it->second.joined = false;
                if (it->second.decoder == mru_decoder)
                    mru_decoder = NULL;
                if (it->second.decoder != NULL) {
                    delete it->second.decoder;
                    it->second.decoder = NULL;
                }
            }
            break;
        }

        //  New peer. Add it to the list of know but unjoint peers.
        if (it == peers.end ()) {
            peer_info_t peer_info = {false, NULL};
            it = peers.insert (peers_t::value_type (*tsi, peer_info)).first;
        }

        //  Read the offset of the fist message in the current packet.
        xs_assert ((size_t) received >= sizeof (uint16_t));
        uint16_t offset = get_uint16 (data);
        data += sizeof (uint16_t);
        received -= sizeof (uint16_t);

        //  Join the stream if needed.
        if (!it->second.joined) {

            //  There is no beginning of the message in current packet.
            //  Ignore the data.
            if (offset == 0xffff)
                continue;

            xs_assert (offset <= received);
            xs_assert (it->second.decoder == NULL);

            //  We have to move data to the begining of the first message.
            data += offset;
            received -= offset;

            //  Mark the stream as joined.
            it->second.joined = true;

            //  Create and connect decoder for the peer.
            it->second.decoder = new (std::nothrow) decoder_t (0,
                options.maxmsgsize);
            alloc_assert (it->second.decoder);
            it->second.decoder->set_session (session);
        }

        mru_decoder = it->second.decoder;

        //  Push all the data to the decoder.
        ssize_t processed = it->second.decoder->process_buffer (data, received);
        if (processed < received) {
            //  Save some state so we can resume the decoding process later.
            pending_bytes = received - processed;
            pending_ptr = data + processed;
            //  Stop polling.
            reset_pollin (pipe_handle);
            reset_pollin (socket_handle);

            //  Reset outstanding timer.
            if (rx_timer) {
                rm_timer (rx_timer);
                rx_timer = NULL;
            }

            break;
        }
    }

    //  Flush any messages decoder may have produced.
    session->flush ();
}
uint16 BNEP_REGISTER_REQ_T_PDU::get_flags() const
{
    return get_uint16 ( BNEP_REGISTER_REQ_T_flags );
}
uint16 BNEP_REGISTER_REQ_T_PDU::get_phandle() const
{
    return get_uint16 ( BNEP_REGISTER_REQ_T_phandle );
}
uint16 BNEP_CONNECT_IND_T_PDU::get_loc_uuid() const
{
    return get_uint16 ( BNEP_CONNECT_IND_T_loc_uuid );
}
uint16 BNEP_CONNECT_REQ_T_PDU::get_flags() const
{
    return get_uint16 ( BNEP_CONNECT_REQ_T_flags );
}
uint16 BNEP_CONNECT_IND_T_PDU::get_status() const
{
    return get_uint16 ( BNEP_CONNECT_IND_T_status );
}
uint16 BNEP_FLOW_IND_T_PDU::get_free() const
{
    return get_uint16 ( BNEP_FLOW_IND_T_free );
}
uint16 BNEP_IGNORE_REQ_T_PDU::get_ether_type() const
{
    return get_uint16 ( BNEP_IGNORE_REQ_T_ether_type );
}
Beispiel #15
0
/** Unpack <b>tag</b> into addr, port, and circ_id.
 */
static void
tag_unpack(const char *tag, uint64_t *chan_id, circid_t *circ_id)
{
  *chan_id = get_uint64(tag);
  *circ_id = get_uint16(tag+8);
}
uint16 BNEP_HCI_SWITCH_ROLE_RSP_T_PDU::get_phandle() const
{
    return get_uint16 ( BNEP_HCI_SWITCH_ROLE_RSP_T_phandle );
}
Beispiel #17
0
/*
 * receive Information
 */
int
isakmp_info_recv(struct ph1handle *iph1, rc_vchar_t *msg0)
{
	rc_vchar_t *msg = NULL;
	struct isakmp *isakmp;
	struct isakmp_gen *gen;
	void *p;
	rc_vchar_t *hash, *payload;
	struct isakmp_gen *nd;
	uint8_t np;
	int encrypted;

	plog(PLOG_DEBUG, PLOGLOC, NULL, "receive Information.\n");

	encrypted = ISSET(((struct isakmp *)msg0->v)->flags, ISAKMP_FLAG_E);

	/* Use new IV to decrypt Informational message. */
	if (encrypted) {
		struct isakmp_ivm *ivm;

		if (iph1->ivm == NULL) {
			plog(PLOG_INTERR, PLOGLOC, NULL, "iph1->ivm == NULL\n");
			return -1;
		}

		/* compute IV */
		ivm = oakley_newiv2(iph1, ((struct isakmp *)msg0->v)->msgid);
		if (ivm == NULL)
			return -1;

		msg = oakley_do_decrypt(iph1, msg0, ivm->iv, ivm->ive);
		oakley_delivm(ivm);
		if (msg == NULL)
			return -1;

	} else
		msg = rc_vdup(msg0);

	/* Safety check */
	if (msg->l < sizeof(*isakmp) + sizeof(*gen)) {
		plog(PLOG_PROTOERR, PLOGLOC, NULL, 
			"ignore information because the "
			"message is way too short\n");
		goto end;
	}

	isakmp = (struct isakmp *)msg->v;
	gen = (struct isakmp_gen *)((caddr_t)isakmp + sizeof(struct isakmp));
	np = gen->np;

	if (encrypted) {
		if (isakmp->np != ISAKMP_NPTYPE_HASH) {
			plog(PLOG_PROTOERR, PLOGLOC, NULL,
			    "ignore information because the "
			    "message has no hash payload.\n");
			goto end;
		}

		if (iph1->status != PHASE1ST_ESTABLISHED) {
			plog(PLOG_PROTOERR, PLOGLOC, NULL,
			    "ignore information because ISAKMP-SA "
			    "has not been established yet.\n");
			goto end;
		}
		
		/* Safety check */
		if (msg->l < sizeof(*isakmp) + get_uint16(&gen->len) + sizeof(*nd)) {
			plog(PLOG_PROTOERR, PLOGLOC, NULL, 
				"ignore information because the "
				"message is too short\n");
			goto end;
		}

		p = (caddr_t) gen + sizeof(struct isakmp_gen);
		nd = (struct isakmp_gen *) ((caddr_t) gen + get_uint16(&gen->len));

		/* nd length check */
		if (get_uint16(&nd->len) > msg->l - (sizeof(struct isakmp) +
		    get_uint16(&gen->len))) {
			plog(PLOG_PROTOERR, PLOGLOC, NULL,
				 "too long payload length (broken message?)\n");
			goto end;
		}

		if (get_uint16(&nd->len) < sizeof(*nd)) {
			plog(PLOG_PROTOERR, PLOGLOC, NULL,
				"too short payload length (broken message?)\n");
			goto end;
		}

		payload = rc_vmalloc(get_uint16(&nd->len));
		if (payload == NULL) {
			plog(PLOG_INTERR, PLOGLOC, NULL,
			    "cannot allocate memory\n");
			goto end;
		}

		memcpy(payload->v, (caddr_t) nd, get_uint16(&nd->len));

		/* compute HASH */
		hash = oakley_compute_hash1(iph1, isakmp->msgid, payload);
		if (hash == NULL) {
			plog(PLOG_INTERR, PLOGLOC, NULL,
			    "cannot compute hash\n");

			rc_vfree(payload);
			goto end;
		}
		
		if (get_uint16(&gen->len) - sizeof(struct isakmp_gen) != hash->l) {
			plog(PLOG_PROTOERR, PLOGLOC, NULL,
			    "ignore information due to hash length mismatch\n");

			rc_vfree(hash);
			rc_vfree(payload);
			goto end;
		}

		if (memcmp(p, hash->v, hash->l) != 0) {
			plog(PLOG_PROTOERR, PLOGLOC, NULL,
			    "ignore information due to hash mismatch\n");

			rc_vfree(hash);
			rc_vfree(payload);
			goto end;
		}

		plog(PLOG_DEBUG, PLOGLOC, NULL, "hash validated.\n");

		rc_vfree(hash);
		rc_vfree(payload);
	} else {
		/* make sure the packet was encrypted after the beginning of phase 1. */
		switch (iph1->etype) {
		case ISAKMP_ETYPE_AGG:
		case ISAKMP_ETYPE_BASE:
		case ISAKMP_ETYPE_IDENT:
			if ((iph1->side == INITIATOR && iph1->status < PHASE1ST_MSG3SENT)
			 || (iph1->side == RESPONDER && iph1->status < PHASE1ST_MSG2SENT)) {
				break;
			}
			/*FALLTHRU*/
		default:
			plog(PLOG_PROTOERR, PLOGLOC, 0,
				"received %s payload is not encrypted\n",
				s_isakmp_nptype(isakmp->np));
			goto end;
		}
	}

	switch (np) {
	case ISAKMP_NPTYPE_N:
		if ( encrypted )
			isakmp_info_recv_n(iph1, msg);
		else 
			plog(PLOG_PROTOWARN, PLOGLOC, 0,
			     "received unencrypted Notify payload, ignored\n");
		break;
	case ISAKMP_NPTYPE_D:
		if ( encrypted )
			isakmp_info_recv_d(iph1, msg);
		else
			plog(PLOG_PROTOWARN, PLOGLOC, 0,
			     "received unencrypted Delete payload, ignored\n");
		break;
	case ISAKMP_NPTYPE_NONCE:
		/* XXX to be 6.4.2 ike-01.txt */
		/* XXX IV is to be synchronized. */
		plog(PLOG_PROTOERR, PLOGLOC, 0,
			"ignore Acknowledged Informational\n");
		break;
	default:
		/* don't send information, see isakmp_ident_r1() */
		plog(PLOG_PROTOERR, PLOGLOC, 0,
			"reject the packet, "
			"received unexpected payload type %s.\n",
			s_isakmp_nptype(gen->np));
		goto end;
	}

    end:
	if (msg != NULL)
		rc_vfree(msg);
	return 0;
}
Beispiel #18
0
int
get_target_port_group(struct path * pp, unsigned int timeout)
{
	unsigned char		*buf;
	struct vpd83_data *	vpd83;
	struct vpd83_dscr *	dscr;
	int			rc;
	int			buflen, scsi_buflen;

	buflen = 4096;
	buf = (unsigned char *)malloc(buflen);
	if (!buf) {
		PRINT_DEBUG("malloc failed: could not allocate"
			     "%u bytes\n", buflen);
		return -RTPG_RTPG_FAILED;
	}

	memset(buf, 0, buflen);

	rc = get_sysfs_pg83(pp, buf, buflen);

	if (rc < 0) {
		rc = do_inquiry(pp->fd, 1, 0x83, buf, buflen, timeout);
		if (rc < 0)
			goto out;

		scsi_buflen = (buf[2] << 8 | buf[3]) + 4;
		/* Paranoia */
		if (scsi_buflen >= USHRT_MAX)
			scsi_buflen = USHRT_MAX;
		if (buflen < scsi_buflen) {
			free(buf);
			buf = (unsigned char *)malloc(scsi_buflen);
			if (!buf) {
				PRINT_DEBUG("malloc failed: could not allocate"
					    "%u bytes\n", scsi_buflen);
				return -RTPG_RTPG_FAILED;
			}
			buflen = scsi_buflen;
			memset(buf, 0, buflen);
			rc = do_inquiry(pp->fd, 1, 0x83, buf, buflen, timeout);
			if (rc < 0)
				goto out;
		}
	}

	vpd83 = (struct vpd83_data *) buf;
	rc = -RTPG_NO_TPG_IDENTIFIER;
	FOR_EACH_VPD83_DSCR(vpd83, dscr) {
		if (vpd83_dscr_istype(dscr, IDTYPE_TARGET_PORT_GROUP)) {
			struct vpd83_tpg_dscr *p;
			if (rc != -RTPG_NO_TPG_IDENTIFIER) {
				PRINT_DEBUG("get_target_port_group: more "
					    "than one TPG identifier found!\n");
				continue;
			}
			p  = (struct vpd83_tpg_dscr *)dscr->data;
			rc = get_uint16(p->tpg);
		}
	}

	if (rc == -RTPG_NO_TPG_IDENTIFIER) {
		PRINT_DEBUG("get_target_port_group: "
			    "no TPG identifier found!\n");
	}
out:
	free(buf);
	return rc;
}
Beispiel #19
0
void zmq::pgm_receiver_t::in_event ()
{
    // Read data from the underlying pgm_socket.
    unsigned char *data = NULL;
    const pgm_tsi_t *tsi = NULL;

    //  TODO: This loop can effectively block other engines in the same I/O
    //  thread in the case of high load.
    while (true) {

        //  Get new batch of data.
        ssize_t received = pgm_socket.receive ((void**) &data, &tsi);

        //  No data to process. This may happen if the packet received is
        //  neither ODATA nor ODATA.
        if (received == 0)
            break;

        //  Find the peer based on its TSI.
        peers_t::iterator it = peers.find (*tsi);

        //  Data loss. Delete decoder and mark the peer as disjoint.
        if (received == -1) {
            zmq_assert (it != peers.end ());
            it->second.joined = false;
            if (it->second.decoder != NULL) {
                delete it->second.decoder;
                it->second.decoder = NULL;
            }
            break;
        }

        //  New peer. Add it to the list of know but unjoint peers.
        if (it == peers.end ()) {
            peer_info_t peer_info = {false, NULL};
            it = peers.insert (std::make_pair (*tsi, peer_info)).first;
        }

        //  Read the offset of the fist message in the current packet.
        zmq_assert ((size_t) received >= sizeof (uint16_t));
        uint16_t offset = get_uint16 (data);
        data += sizeof (uint16_t);
        received -= sizeof (uint16_t);

        //  Join the stream if needed.
        if (!it->second.joined) {

            //  There is no beginning of the message in current packet.
            //  Ignore the data.
            if (offset == 0xffff)
                continue;

            zmq_assert (offset <= received);
            zmq_assert (it->second.decoder == NULL);

            //  We have to move data to the begining of the first message.
            data += offset;
            received -= offset;

            //  Mark the stream as joined.
            it->second.joined = true;

            //  Create and connect decoder for the peer.
            it->second.decoder = new (std::nothrow) zmq_decoder_t (0, NULL, 0);
            it->second.decoder->set_inout (inout);
        }

        //  Push all the data to the decoder.
        //  TODO: process_buffer may not process entire buffer!
        ssize_t processed = it->second.decoder->process_buffer (data, received);
        zmq_assert (processed == received);
    }

    //  Flush any messages decoder may have produced.
    inout->flush ();
}
Beispiel #20
0
void zmq::pgm_receiver_t::in_event ()
{
    // Read data from the underlying pgm_socket.
    const pgm_tsi_t *tsi = NULL;

    if (has_rx_timer) {
        cancel_timer (rx_timer_id);
        has_rx_timer = false;
    }

    //  TODO: This loop can effectively block other engines in the same I/O
    //  thread in the case of high load.
    while (true) {

        //  Get new batch of data.
        //  Note the workaround made not to break strict-aliasing rules.
        void *tmp = NULL;
        ssize_t received = pgm_socket.receive (&tmp, &tsi);
        inpos = (unsigned char*) tmp;

        //  No data to process. This may happen if the packet received is
        //  neither ODATA nor ODATA.
        if (received == 0) {
            if (errno == ENOMEM || errno == EBUSY) {
                const long timeout = pgm_socket.get_rx_timeout ();
                add_timer (timeout, rx_timer_id);
                has_rx_timer = true;
            }
            break;
        }

        //  Find the peer based on its TSI.
        peers_t::iterator it = peers.find (*tsi);

        //  Data loss. Delete decoder and mark the peer as disjoint.
        if (received == -1) {
            if (it != peers.end ()) {
                it->second.joined = false;
                if (it->second.decoder != NULL) {
                    delete it->second.decoder;
                    it->second.decoder = NULL;
                }
            }
            break;
        }

        //  New peer. Add it to the list of know but unjoint peers.
        if (it == peers.end ()) {
            peer_info_t peer_info = {false, NULL};
            it = peers.insert (peers_t::value_type (*tsi, peer_info)).first;
        }

        insize = static_cast <size_t> (received);

        //  Read the offset of the fist message in the current packet.
        zmq_assert (insize >= sizeof (uint16_t));
        uint16_t offset = get_uint16 (inpos);
        inpos += sizeof (uint16_t);
        insize -= sizeof (uint16_t);

        //  Join the stream if needed.
        if (!it->second.joined) {

            //  There is no beginning of the message in current packet.
            //  Ignore the data.
            if (offset == 0xffff)
                continue;

            zmq_assert (offset <= insize);
            zmq_assert (it->second.decoder == NULL);

            //  We have to move data to the begining of the first message.
            inpos += offset;
            insize -= offset;

            //  Mark the stream as joined.
            it->second.joined = true;

            //  Create and connect decoder for the peer.
            it->second.decoder = new (std::nothrow)
                v1_decoder_t (0, options.maxmsgsize);
            alloc_assert (it->second.decoder);
        }

        int rc = process_input (it->second.decoder);
        if (rc == -1) {
            if (errno == EAGAIN) {
                active_tsi = tsi;

                //  Stop polling.
                reset_pollin (pipe_handle);
                reset_pollin (socket_handle);

                break;
            }

            it->second.joined = false;
            delete it->second.decoder;
            it->second.decoder = NULL;
            insize = 0;
        }
    }

    //  Flush any messages decoder may have produced.
    session->flush ();
}
Beispiel #21
0
/* Process a buffer of PCL XL commands. */
int
px_process(px_parser_state_t * st, px_state_t * pxs, stream_cursor_read * pr)
{
    const byte *orig_p = pr->ptr;
    const byte *next_p = orig_p;        /* start of data not copied to saved */
    const byte *p;
    const byte *rlimit;
    px_value_t *sp = &st->stack[st->stack_count];

#define stack_limit &st->stack[max_stack - 1]
    gs_memory_t *memory = st->memory;
    int code = 0;
    uint left;
    uint min_left;
    px_tag_t tag;
    const px_tag_syntax_t *syntax = 0;

    st->args.parser = st;
    st->parent_operator_count = 0;      /* in case of error */
    /* Check for leftover data from the previous call. */
  parse:if (st->saved_count) { /* Fill up the saved buffer so we can make progress. */
        int move = min(sizeof(st->saved) - st->saved_count,
                       pr->limit - next_p);

        memcpy(&st->saved[st->saved_count], next_p + 1, move);
        next_p += move;
        p = st->saved - 1;
        rlimit = p + st->saved_count + move;
    } else {                    /* No leftover data, just read from the input. */
        p = next_p;
        rlimit = pr->limit;
    }
  top:if (st->data_left) {     /* We're in the middle of reading an array or data block. */
        if (st->data_proc) {    /* This is a data block. */
            uint avail = min(rlimit - p, st->data_left);
            uint used;

            st->args.source.available = avail;
            st->args.source.data = p + 1;
            code = (*st->data_proc) (&st->args, pxs);
            /* If we get a 'remap_color' error, it means we are dealing with a
             * pattern, and the device supports high level patterns. So we must
             * use our high level pattern implementation.
             */
            if (code == gs_error_Remap_Color) {
                code = px_high_level_pattern(pxs->pgs);
                code = (*st->data_proc) (&st->args, pxs);
            }
            used = st->args.source.data - (p + 1);
#ifdef DEBUG
            if (gs_debug_c('I')) {
                px_value_t data_array;

                data_array.type = pxd_ubyte;
                data_array.value.array.data = p + 1;
                data_array.value.array.size = used;
                trace_array_data(pxs->memory, "data:", &data_array);
            }
#endif
            p = st->args.source.data - 1;
            st->data_left -= used;
            if (code < 0) {
                st->args.source.position = 0;
                goto x;
            } else if ((code == pxNeedData)
                       || (code == pxPassThrough && st->data_left != 0)) {
                code = 0;       /* exit for more data */
                goto x;
            } else {
                st->args.source.position = 0;
                st->data_proc = 0;
                if (st->data_left != 0) {
                    code = gs_note_error(errorExtraData);
                    goto x;
                }
                clear_stack();
            }
        } else {                /* This is an array. */
            uint size = sp->value.array.size;
            uint scale = value_size(sp);
            uint nbytes = size * scale;
            byte *dest =
                (byte *) sp->value.array.data + nbytes - st->data_left;

            left = rlimit - p;
            if (left < st->data_left) { /* We still don't have enough data to fill the array. */
                memcpy(dest, p + 1, left);
                st->data_left -= left;
                p = rlimit;
                code = 0;
                goto x;
            }
            /* Complete the array and continue parsing. */
            memcpy(dest, p + 1, st->data_left);
            trace_array(memory, sp);
            p += st->data_left;
        }
        st->data_left = 0;
    } else if (st->data_proc) { /* An operator is awaiting data. */
        /* Skip white space until we find some. */
        code = 0;               /* in case we exit */
        /* special case - VendorUnique has a length attribute which
           we've already parsed and error checked */
        if (st->data_proc == pxVendorUnique) {
            st->data_left =
                st->stack[st->attribute_indices[pxaVUDataLength]].value.i;
            goto top;
        } else {
            while ((left = rlimit - p) != 0) {
                switch ((tag = p[1])) {
                case pxtNull:
                case pxtHT:
                case pxtLF:
                case pxtVT:
                case pxtFF:
                case pxtCR:
                    ++p;
                    continue;
                case pxt_dataLength:
                    if (left < 5)
                        goto x; /* can't look ahead */
                    st->data_left = get_uint32(st, p + 2);
                    if_debug2m('i', memory, "tag=  0x%2x  data, length %u\n",
                               p[1], st->data_left);
                    p += 5;
                    goto top;
                case pxt_dataLengthByte:
                    if (left < 2)
                        goto x; /* can't look ahead */
                    st->data_left = p[2];
                    if_debug2m('i', memory, "tag=  0x%2x  data, length %u\n",
                               p[1], st->data_left);
                    p += 2;
                    goto top;
                default:
                    {
                        code = gs_note_error(errorMissingData);
                        goto x;
                    }
                }
            }
        }
    }
    st->args.source.position = 0;
    st->args.source.available = 0;
    while ((left = rlimit - p) != 0 &&
           left >= (min_left = (syntax = &tag_syntax[tag = p[1]])->min_input)
        ) {
        int count;

#ifdef DEBUG
        if (gs_debug_c('i')) {
            dmprintf1(memory, "tag=  0x%02x  ", tag);
            if (tag == pxt_attr_ubyte || tag == pxt_attr_uint16) {
                px_attribute_t attr =
                    (tag == pxt_attr_ubyte ? p[2] : get_uint16(st, p + 2));
                const char *aname = px_attribute_names[attr];

                if (aname)
                    dmprintf1(memory, "   @%s\n", aname);
                else
                    dmprintf1(memory, "   attribute %u ???\n", attr);
            } else {
                const char *format;
                const char *tname;
                bool operator = false;

                if (tag < 0x40)
                    format = "%s\n", tname = px_tag_0_names[tag];
                else if (tag < 0xc0)
                    format = "%s", tname = px_operator_names[tag - 0x40],
                        operator = true;
                else {
                    tname = px_tag_c0_names[tag - 0xc0];
                    if (tag < 0xf0)
                        format = "      %s";    /* data values follow */
                    else
                        format = "%s\n";
                }
                if (tname) {
                    dmprintf1(memory, format, tname);
                    if (operator)
                        dmprintf1(memory, " (%ld)\n", st->operator_count + 1);
                } else
                    dmputs(memory, "???\n");
            }
        }
#endif
        if ((st->macro_state & syntax->state_mask) != syntax->state_value) {
            /*
             * We should probably distinguish here between
             * out-of-context operators and illegal tags, but it's too
             * much trouble.
             */
            code = gs_note_error(errorIllegalOperatorSequence);
            if (tag >= 0x40 && tag < 0xc0)
                st->last_operator = tag;
            goto x;
        }
        st->macro_state ^= syntax->state_transition;
        switch (tag >> 3) {
            case 0:
                switch (tag) {
                    case pxtNull:
                        ++p;
                        continue;
                    default:
                        break;
                }
                break;
            case 1:
                switch (tag) {
                    case pxtHT:
                    case pxtLF:
                    case pxtVT:
                    case pxtFF:
                    case pxtCR:
                        ++p;
                        continue;
                    default:
                        break;
                }
                break;
            case 3:
                if (tag == pxt1b) {     /* ESC *//* Check for UEL */
                    if (memcmp(p + 1, "\033%-12345X", min(left, 9)))
                        break;  /* not UEL, error */
                    if (left < 9)
                        goto x; /* need more data */
                    p += 9;
                    code = e_ExitLanguage;
                    goto x;
                }
                break;
            case 4:
                switch (tag) {
                    case pxtSpace:
                        /* break; will error, compatible with lj */
                        /* ++p;continue; silently ignores the space */
                        ++p;
                        continue;
                    default:
                        break;
                }
                break;
            case 8:
            case 9:
            case 10:
            case 11:
            case 12:
            case 13:
            case 14:
            case 15:
            case 16:
            case 17:
            case 18:
            case 19:
            case 20:
            case 21:
            case 22:
            case 23:
                /* Operators */
                /* Make sure that we have all the required attributes, */
                /* and no attributes that are neither required nor */
                /* optional.  (It's up to the operator to make any */
                /* more precise checks than this. */
                st->operator_count++;
                /* if this is a passthrough operator we have to tell
                   the passthrough module if this operator was
                   preceded by another passthrough operator or a
                   different xl operator */
                if (tag == pxtPassThrough) {
                    pxpcl_passthroughcontiguous(st->last_operator == tag);
                } else if (st->last_operator == pxtPassThrough) {
                    pxpcl_endpassthroughcontiguous(pxs);
                }

                st->last_operator = tag;
                {
                    const px_operator_definition_t *pod =
                        &px_operator_definitions[tag - 0x40];
                    int left = sp - st->stack;
                    const byte /*px_attribute_t */  * pal = pod->attrs;
                    px_value_t **ppv = st->args.pv;
                    bool required = true;
                    code = 0;
                    /*
                     * Scan the attributes.  Illegal attributes take priority
                     * over missing attributes, which in turn take priority
                     * over illegal data types.
                     */
                    for (;; ++pal, ++ppv) {
                        px_attribute_t attr = *pal;
                        uint index;

                        if (!attr) {    /*
                                         * We've reached the end of either the required or
                                         * the optional attribute list.
                                         */
                            if (!required)
                                break;
                            required = false;
                            --ppv;      /* cancel incrementing */
                            continue;
                        }
                        if ((index = st->attribute_indices[attr]) == 0) {
                            if (required)
                                code = gs_note_error(errorMissingAttribute);
                            else
                                *ppv = 0;
                        } else {        /* Check the attribute data type and value. */
                            px_value_t *pv = *ppv = &st->stack[index];
                            const px_attr_value_type_t *pavt =
                                &px_attr_value_types[attr];
                            int acode;

                            if ((~pavt->mask & pv->type &
                                 (pxd_structure | pxd_representation)) ||
                                (pavt->mask == (pxd_scalar | pxd_ubyte) &&
                                 (pv->value.i < 0
                                  || pv->value.i > pavt->limit))
                                ) {
                                if (code >= 0)
                                    code =
                                        gs_note_error
                                        (errorIllegalAttributeDataType);
                            }
                            if (pavt->proc != 0
                                && (acode = (*pavt->proc) (pv)) < 0) {
                                if (code >= 0)
                                    code = acode;
                            }
                            --left;
                        }
                    }

                    /* Make sure there are no attributes left over. */
                    if (left)
                        code = gs_note_error(errorIllegalAttribute);
                    if (code >= 0) {
                        st->args.source.phase = 0;
                        code = (*pod->proc) (&st->args, pxs);
                        /* If we get a 'remap_color' error, it means we are dealing with a
                         * pattern, and the device supports high level patterns. So we must
                         * use our high level pattern implementation.
                         */
                        if (code == gs_error_Remap_Color) {
                            code = px_high_level_pattern(pxs->pgs);
                            if (code < 0)
                                goto x;
                            code = (*pod->proc) (&st->args, pxs);
                        }
                    }
                    if (code < 0)
                        goto x;
                    /* Check whether the operator wanted source data. */
                    if (code == pxNeedData) {
                        if (!pxs->data_source_open) {
                            code = gs_note_error(errorDataSourceNotOpen);
                            goto x;
                        }
                        st->data_proc = pod->proc;
                        ++p;
                        goto top;
                    }
                }
                clear_stack();
                ++p;
                continue;
            case 24:
                sp[1].type = pxd_scalar;
                count = 1;
                goto data;
            case 26:
                sp[1].type = pxd_xy;
                count = 2;
                goto data;
            case 28:
                sp[1].type = pxd_box;
                count = 4;
                goto data;
                /* Scalar, point, and box data */
              data:{
                    int i;

                    if (sp == stack_limit) {
                        code = gs_note_error(errorInternalOverflow);
                        goto x;
                    }
                    ++sp;
                    sp->attribute = 0;
                    p += 2;
#ifdef DEBUG
#  define trace_scalar(mem, format, cast, alt)\
                  if ( gs_debug_c('i') )\
                    trace_data(mem, format, cast, sp->value.alt, count)
#else
#  define trace_scalar(mem, format, cast, alt) DO_NOTHING
#endif
                    switch (tag & 7) {
                        case pxt_ubyte & 7:
                            sp->type |= pxd_ubyte;
                            for (i = 0; i < count; ++p, ++i)
                                sp->value.ia[i] = *p;
                          dux:trace_scalar(pxs->memory, " %lu", ulong,
                                         ia);
                            --p;
                            continue;
                        case pxt_uint16 & 7:
                            sp->type |= pxd_uint16;
                            for (i = 0; i < count; p += 2, ++i)
                                sp->value.ia[i] = get_uint16(st, p);
                            goto dux;
                        case pxt_uint32 & 7:
                            sp->type |= pxd_uint32;
                            for (i = 0; i < count; p += 4, ++i)
                                sp->value.ia[i] = get_uint32(st, p);
                            goto dux;
                        case pxt_sint16 & 7:
                            sp->type |= pxd_sint16;
                            for (i = 0; i < count; p += 2, ++i)
                                sp->value.ia[i] = get_sint16(st, p);
                          dsx:trace_scalar(pxs->memory, " %ld", long,
                                         ia);
                            --p;
                            continue;
                        case pxt_sint32 & 7:
                            sp->type |= pxd_sint32;
                            for (i = 0; i < count; p += 4, ++i)
                                sp->value.ia[i] = get_sint32(st, p);
                            goto dsx;
                        case pxt_real32 & 7:
                            sp->type |= pxd_real32;
                            for (i = 0; i < count; p += 4, ++i)
                                sp->value.ra[i] = get_real32(st, p);
                            trace_scalar(pxs->memory, " %g", double, ra);

                            --p;
                            continue;
                        default:
                            break;
                    }
                }
                break;
            case 25:
                /* Array data */
                {
                    const byte *dp;
                    uint nbytes;

                    if (sp == stack_limit) {
                        code = gs_note_error(errorInternalOverflow);
                        goto x;
                    }
                    switch (p[2]) {
                        case pxt_ubyte:
                            sp[1].value.array.size = p[3];
                            dp = p + 4;
                            break;
                        case pxt_uint16:
                            if (left < 4) {
                                if_debug0m('i', memory, "...\n");
                                /* Undo the state transition. */
                                st->macro_state ^= syntax->state_transition;
                                goto x;
                            }
                            sp[1].value.array.size = get_uint16(st, p + 3);
                            dp = p + 5;
                            break;
                        default:
                            st->last_operator = tag;    /* for error message */
                            code = gs_note_error(errorIllegalTag);
                            goto x;
                    }
                    nbytes = sp[1].value.array.size;
                    if_debug1m('i', memory, "[%u]\n", sp[1].value.array.size);
                    switch (tag) {
                        case pxt_ubyte_array:
                            sp[1].type = pxd_array | pxd_ubyte;
                          array:++sp;
                            if (st->big_endian)
                                sp->type |= pxd_big_endian;
                            sp->value.array.data = dp;
                            sp->attribute = 0;
                            /* Check whether we have enough data for the entire */
                            /* array. */
                            if (rlimit + 1 - dp < nbytes) {     /* Exit now, continue reading when we return. */
                                uint avail = rlimit + 1 - dp;

                                code = px_save_array(sp, pxs, "partial array",
                                                     avail);
                                if (code < 0)
                                    goto x;
                                sp->type |= pxd_on_heap;
                                st->data_left = nbytes - avail;
                                st->data_proc = 0;
                                p = rlimit;
                                goto x;
                            }
                            p = dp + nbytes - 1;
                            trace_array(memory, sp);
                            continue;
                        case pxt_uint16_array:
                            sp[1].type = pxd_array | pxd_uint16;
                          a16:nbytes <<= 1;
                            goto array;
                        case pxt_uint32_array:
                            sp[1].type = pxd_array | pxd_uint32;
                          a32:nbytes <<= 2;
                            goto array;
                        case pxt_sint16_array:
                            sp[1].type = pxd_array | pxd_sint16;
                            goto a16;
                        case pxt_sint32_array:
                            sp[1].type = pxd_array | pxd_sint32;
                            goto a32;
                        case pxt_real32_array:
                            sp[1].type = pxd_array | pxd_real32;
                            goto a32;
                        default:
                            break;
                    }
                    break;
                }
                break;
            case 31:
                {
                    px_attribute_t attr;
                    const byte *pnext;

                    switch (tag) {
                        case pxt_attr_ubyte:
                            attr = p[2];
                            pnext = p + 2;
                            goto a;
                        case pxt_attr_uint16:
                            attr = get_uint16(st, p + 2);
                            pnext = p + 3;
                          a:if (attr >=
                                px_attribute_next)
                                break;
                            /*
                             * We could check the attribute value type here, but
                             * in order to match the behavior of the H-P printers,
                             * we don't do it until we see the operator.
                             *
                             * It is legal to specify the same attribute more than
                             * once; the last value has priority.  If this happens,
                             * since the order of attributes doesn't matter, we can
                             * just replace the former value on the stack.
                             */
                            sp->attribute = attr;
                            if (st->attribute_indices[attr] != 0) {
                                px_value_t *old_sp =
                                    &st->stack[st->attribute_indices[attr]];
                                /* If the old value is on the heap, free it. */
                                if (old_sp->type & pxd_on_heap)
                                    gs_free_object(memory,
                                                   (void *)old_sp->value.
                                                   array.data,
                                                   "old value for duplicate attribute");
                                *old_sp = *sp--;
                            } else
                                st->attribute_indices[attr] = sp - st->stack;
                            p = pnext;
                            continue;
                        case pxt_dataLength:
                            /*
                             * Unexpected data length operators are normally not
                             * allowed, but there might be a zero-length data
                             * block immediately following a zero-size image,
                             * which doesn't ask for any data.
                             */
                            if (uint32at(p + 2, true /*arbitrary */ ) == 0) {
                                p += 5;
                                continue;
                            }
                            break;
                        case pxt_dataLengthByte:
                            /* See the comment under pxt_dataLength above. */
                            if (p[2] == 0) {
                                p += 2;
                                continue;
                            }
                            break;
                        default:
                            break;
                    }
                }
                break;
            default:
                break;
        }
        /* Unknown tag value.  Report an error. */
        st->last_operator = tag;        /* for error message */
        code = gs_note_error(errorIllegalTag);
        break;
    }
  x:                           /* Save any leftover input. */
    left = rlimit - p;
    if (rlimit != pr->limit) {  /* We were reading saved input. */
        if (left <= next_p - orig_p) {  /* We finished reading the previously saved input. */
            /* Continue reading current input, unless we got an error. */
            p = next_p -= left;
            rlimit = pr->limit;
            st->saved_count = 0;
            if (code >= 0)
                goto parse;
        } else {                /* There's still some previously saved input left over. */
            memmove(st->saved, p + 1, st->saved_count = left);
            p = next_p;
            rlimit = pr->limit;
            left = rlimit - p;
        }
    }
    /* Except in case of error, save any remaining input. */
    if (code >= 0) {
        if (left + st->saved_count > sizeof(st->saved)) {       /* Fatal error -- shouldn't happen! */
            code = gs_note_error(errorInternalOverflow);
            st->saved_count = 0;
        } else {
            memcpy(&st->saved[st->saved_count], p + 1, left);
            st->saved_count += left;
            p = rlimit;
        }
    }
    pr->ptr = p;
    st->stack_count = sp - st->stack;
    /* Move to the heap any arrays whose data was being referenced */
    /* directly in the input buffer. */
    for (; sp > st->stack; --sp)
        if ((sp->type & (pxd_array | pxd_on_heap)) == pxd_array) {
            int code = px_save_array(sp, pxs, "px stack array to heap",
                                     sp->value.array.size * value_size(sp));

            if (code < 0)
                break;
            sp->type |= pxd_on_heap;
        }
    if (code < 0 && syntax != 0) {      /* Undo the state transition. */
        st->macro_state ^= syntax->state_transition;
    }
    return code;
}
Beispiel #22
0
uint16_t sonyPS2_buttonsRaw(const SONY_PS2* controller){
	uint16_t rtn = get_uint16(controller->buffer,0);
	return rtn ^= 0xFFFFU;		// invert the bits
}
Beispiel #23
0
/*
   read_directory(archive) -> files dict (new reference)

   Given a path to a Zip archive, build a dict, mapping file names
   (local to the archive, using SEP as a separator) to toc entries.

   A toc_entry is a tuple:

   (__file__,      # value to use for __file__, available for all files,
                   # encoded to the filesystem encoding
    compress,      # compression kind; 0 for uncompressed
    data_size,     # size of compressed data on disk
    file_size,     # size of decompressed data
    file_offset,   # offset of file header from start of archive
    time,          # mod time of file (in dos format)
    date,          # mod data of file (in dos format)
    crc,           # crc checksum of the data
   )

   Directories can be recognized by the trailing SEP in the name,
   data_size and file_offset are 0.
*/
static PyObject *
read_directory(PyObject *archive)
{
    PyObject *files = NULL;
    FILE *fp;
    unsigned short flags, compress, time, date, name_size;
    unsigned int crc, data_size, file_size, header_size, header_offset;
    unsigned long file_offset, header_position;
    unsigned long arc_offset;  /* Absolute offset to start of the zip-archive. */
    unsigned int count, i;
    unsigned char buffer[46];
    char name[MAXPATHLEN + 5];
    PyObject *nameobj = NULL;
    PyObject *path;
    const char *charset;
    int bootstrap;
    const char *errmsg = NULL;

    fp = _Py_fopen_obj(archive, "rb");
    if (fp == NULL) {
        if (PyErr_ExceptionMatches(PyExc_OSError)) {
            _PyErr_FormatFromCause(ZipImportError,
                                   "can't open Zip file: %R", archive);
        }
        return NULL;
    }

    if (fseek(fp, -22, SEEK_END) == -1) {
        goto file_error;
    }
    header_position = (unsigned long)ftell(fp);
    if (header_position == (unsigned long)-1) {
        goto file_error;
    }
    assert(header_position <= (unsigned long)LONG_MAX);
    if (fread(buffer, 1, 22, fp) != 22) {
        goto file_error;
    }
    if (get_uint32(buffer) != 0x06054B50u) {
        /* Bad: End of Central Dir signature */
        errmsg = "not a Zip file";
        goto invalid_header;
    }

    header_size = get_uint32(buffer + 12);
    header_offset = get_uint32(buffer + 16);
    if (header_position < header_size) {
        errmsg = "bad central directory size";
        goto invalid_header;
    }
    if (header_position < header_offset) {
        errmsg = "bad central directory offset";
        goto invalid_header;
    }
    if (header_position - header_size < header_offset) {
        errmsg = "bad central directory size or offset";
        goto invalid_header;
    }
    header_position -= header_size;
    arc_offset = header_position - header_offset;

    files = PyDict_New();
    if (files == NULL) {
        goto error;
    }
    /* Start of Central Directory */
    count = 0;
    if (fseek(fp, (long)header_position, 0) == -1) {
        goto file_error;
    }
    for (;;) {
        PyObject *t;
        size_t n;
        int err;

        n = fread(buffer, 1, 46, fp);
        if (n < 4) {
            goto eof_error;
        }
        /* Start of file header */
        if (get_uint32(buffer) != 0x02014B50u) {
            break;              /* Bad: Central Dir File Header */
        }
        if (n != 46) {
            goto eof_error;
        }
        flags = get_uint16(buffer + 8);
        compress = get_uint16(buffer + 10);
        time = get_uint16(buffer + 12);
        date = get_uint16(buffer + 14);
        crc = get_uint32(buffer + 16);
        data_size = get_uint32(buffer + 20);
        file_size = get_uint32(buffer + 24);
        name_size = get_uint16(buffer + 28);
        header_size = (unsigned int)name_size +
           get_uint16(buffer + 30) /* extra field */ +
           get_uint16(buffer + 32) /* comment */;

        file_offset = get_uint32(buffer + 42);
        if (file_offset > header_offset) {
            errmsg = "bad local header offset";
            goto invalid_header;
        }
        file_offset += arc_offset;

        if (name_size > MAXPATHLEN) {
            name_size = MAXPATHLEN;
        }
        if (fread(name, 1, name_size, fp) != name_size) {
            goto file_error;
        }
        name[name_size] = '\0';  /* Add terminating null byte */
        if (SEP != '/') {
            for (i = 0; i < name_size; i++) {
                if (name[i] == '/') {
                    name[i] = SEP;
                }
            }
        }
        /* Skip the rest of the header.
         * On Windows, calling fseek to skip over the fields we don't use is
         * slower than reading the data because fseek flushes stdio's
         * internal buffers.  See issue #8745. */
        assert(header_size <= 3*0xFFFFu);
        for (i = name_size; i < header_size; i++) {
            if (getc(fp) == EOF) {
                goto file_error;
            }
        }

        bootstrap = 0;
        if (flags & 0x0800) {
            charset = "utf-8";
        }
        else if (!PyThreadState_GET()->interp->codecs_initialized) {
            /* During bootstrap, we may need to load the encodings
               package from a ZIP file. But the cp437 encoding is implemented
               in Python in the encodings package.

               Break out of this dependency by assuming that the path to
               the encodings module is ASCII-only. */
            charset = "ascii";
            bootstrap = 1;
        }
        else {
            charset = "cp437";
        }
        nameobj = PyUnicode_Decode(name, name_size, charset, NULL);
        if (nameobj == NULL) {
            if (bootstrap) {
                PyErr_Format(PyExc_NotImplementedError,
                    "bootstrap issue: python%i%i.zip contains non-ASCII "
                    "filenames without the unicode flag",
                    PY_MAJOR_VERSION, PY_MINOR_VERSION);
            }
            goto error;
        }
        if (PyUnicode_READY(nameobj) == -1) {
            goto error;
        }
        path = PyUnicode_FromFormat("%U%c%U", archive, SEP, nameobj);
        if (path == NULL) {
            goto error;
        }
        t = Py_BuildValue("NHIIkHHI", path, compress, data_size,
                          file_size, file_offset, time, date, crc);
        if (t == NULL) {
            goto error;
        }
        err = PyDict_SetItem(files, nameobj, t);
        Py_CLEAR(nameobj);
        Py_DECREF(t);
        if (err != 0) {
            goto error;
        }
        count++;
    }
    fclose(fp);
    if (Py_VerboseFlag) {
        PySys_FormatStderr("# zipimport: found %u names in %R\n",
                           count, archive);
    }
    return files;

eof_error:
    set_file_error(archive, !ferror(fp));
    goto error;

file_error:
    PyErr_Format(ZipImportError, "can't read Zip file: %R", archive);
    goto error;

invalid_header:
    assert(errmsg != NULL);
    PyErr_Format(ZipImportError, "%s: %R", errmsg, archive);
    goto error;

error:
    fclose(fp);
    Py_XDECREF(files);
    Py_XDECREF(nameobj);
    return NULL;
}
Beispiel #24
0
/** Parse an EXTEND or EXTEND2 cell (according to <b>command</b>) from the
 * <b>payload_length</b> bytes of <b>payload</b> into <b>cell_out</b>. Return
 * 0 on success, -1 on failure. */
int
extend_cell_parse(extend_cell_t *cell_out, const uint8_t command,
                  const uint8_t *payload, size_t payload_length)
{
  const uint8_t *eop;

  memset(cell_out, 0, sizeof(*cell_out));
  if (payload_length > RELAY_PAYLOAD_SIZE)
    return -1;
  eop = payload + payload_length;

  switch (command) {
  case RELAY_COMMAND_EXTEND:
    {
      if (payload_length != 6 + TAP_ONIONSKIN_CHALLENGE_LEN + DIGEST_LEN)
        return -1;

      cell_out->cell_type = RELAY_COMMAND_EXTEND;
      tor_addr_from_ipv4n(&cell_out->orport_ipv4.addr, get_uint32(payload));
      cell_out->orport_ipv4.port = ntohs(get_uint16(payload+4));
      tor_addr_make_unspec(&cell_out->orport_ipv6.addr);
      if (tor_memeq(payload + 6, NTOR_CREATE_MAGIC, 16)) {
        cell_out->create_cell.cell_type = CELL_CREATE2;
        cell_out->create_cell.handshake_type = ONION_HANDSHAKE_TYPE_NTOR;
        cell_out->create_cell.handshake_len = NTOR_ONIONSKIN_LEN;
        memcpy(cell_out->create_cell.onionskin, payload + 22,
               NTOR_ONIONSKIN_LEN);
      } else {
        cell_out->create_cell.cell_type = CELL_CREATE;
        cell_out->create_cell.handshake_type = ONION_HANDSHAKE_TYPE_TAP;
        cell_out->create_cell.handshake_len = TAP_ONIONSKIN_CHALLENGE_LEN;
        memcpy(cell_out->create_cell.onionskin, payload + 6,
               TAP_ONIONSKIN_CHALLENGE_LEN);
      }
      memcpy(cell_out->node_id, payload + 6 + TAP_ONIONSKIN_CHALLENGE_LEN,
             DIGEST_LEN);
      break;
    }
  case RELAY_COMMAND_EXTEND2:
    {
      uint8_t n_specs, spectype, speclen;
      int i;
      int found_ipv4 = 0, found_ipv6 = 0, found_id = 0;
      tor_addr_make_unspec(&cell_out->orport_ipv4.addr);
      tor_addr_make_unspec(&cell_out->orport_ipv6.addr);

      if (payload_length == 0)
        return -1;

      cell_out->cell_type = RELAY_COMMAND_EXTEND2;
      n_specs = *payload++;
      /* Parse the specifiers. We'll only take the first IPv4 and first IPv6
       * address, and the node ID, and ignore everything else */
      for (i = 0; i < n_specs; ++i) {
        if (eop - payload < 2)
          return -1;
        spectype = payload[0];
        speclen = payload[1];
        payload += 2;
        if (eop - payload < speclen)
          return -1;
        switch (spectype) {
        case SPECTYPE_IPV4:
          if (speclen != 6)
            return -1;
          if (!found_ipv4) {
            tor_addr_from_ipv4n(&cell_out->orport_ipv4.addr,
                                get_uint32(payload));
            cell_out->orport_ipv4.port = ntohs(get_uint16(payload+4));
            found_ipv4 = 1;
          }
          break;
        case SPECTYPE_IPV6:
          if (speclen != 18)
            return -1;
          if (!found_ipv6) {
            tor_addr_from_ipv6_bytes(&cell_out->orport_ipv6.addr,
                                     (const char*)payload);
            cell_out->orport_ipv6.port = ntohs(get_uint16(payload+16));
            found_ipv6 = 1;
          }
          break;
        case SPECTYPE_LEGACY_ID:
          if (speclen != 20)
            return -1;
          if (found_id)
            return -1;
          memcpy(cell_out->node_id, payload, 20);
          found_id = 1;
          break;
        }
        payload += speclen;
      }
      if (!found_id || !found_ipv4)
        return -1;
      if (parse_create2_payload(&cell_out->create_cell,payload,eop-payload)<0)
        return -1;
      break;
    }
  default:
    return -1;
  }

  return check_extend_cell(cell_out);
}
Beispiel #25
0
static int _set_res_rec(int *start, int argc, char *argv[],
                        List name_list, List cluster_list,
                        slurmdb_res_rec_t *res)
{
    int i;
    int set = 0;
    int end = 0;
    int command_len = 0;
    int option = 0;

    xassert(res);

    for (i=(*start); i<argc; i++) {
        end = parse_option_end(argv[i]);
        if (!end)
            command_len=strlen(argv[i]);
        else {
            command_len=end-1;
            if (argv[i][end] == '=') {
                option = (int)argv[i][end-1];
                end++;
            }
        }

        if (!strncasecmp(argv[i], "Where", MAX(command_len, 5))) {
            i--;
            break;
        } else if (!end && !strncasecmp(argv[i], "set",
                                        MAX(command_len, 3))) {
            continue;
        } else if (!end
                   || !strncasecmp(argv[i], "Names",
                                   MAX(command_len, 1))
                   || !strncasecmp(argv[i], "Resources",
                                   MAX(command_len, 1))) {
            if (name_list)
                slurm_addto_char_list(name_list, argv[i]+end);
        } else if (!strncasecmp(argv[i], "Clusters",
                                MAX(command_len, 1))) {
            if (cluster_list) {
                slurm_addto_char_list(cluster_list,
                                      argv[i]+end);
                if (sacctmgr_validate_cluster_list(
                            cluster_list) != SLURM_SUCCESS) {
                    exit_code=1;
                    fprintf(stderr,
                            " Need a valid cluster name to "
                            "add a cluster resource.\n");
                }
            } else {
                exit_code=1;
                fprintf(stderr,
                        " Can't modify the cluster "
                        "of an resource\n");
            }
        } else if (!strncasecmp(argv[i], "Count",
                                MAX(command_len, 3))) {
            if (get_uint(argv[i]+end, &res->count,
                         "count") == SLURM_SUCCESS) {
                set = 1;
            }
        } else if (!strncasecmp(argv[i], "Description",
                                MAX(command_len, 1))) {
            if (!res->description)
                res->description =
                    strip_quotes(argv[i]+end, NULL, 1);
            set = 1;
        } else if (!strncasecmp(argv[i], "Flags",
                                MAX(command_len, 2))) {
            res->flags = str_2_res_flags(argv[i]+end, option);
            if (res->flags == SLURMDB_RES_FLAG_NOTSET) {
                char *tmp_char = slurmdb_res_flags_str(
                                     SLURMDB_RES_FLAG_BASE);
                printf(" Unknown Server Resource flag used "
                       "in:\n  '%s'\n"
                       " Valid Server Resource flags are\n"
                       " '%s'\n", argv[i]+end, tmp_char);
                xfree(tmp_char);
                exit_code = 1;
            } else
                set = 1;
        } else if (!strncasecmp(argv[i], "Manager",
                                MAX(command_len, 1))) {
            if (!res->manager)
                res->manager =
                    strip_quotes(argv[i]+end, NULL, 1);
            set = 1;
        } else if (!strncasecmp(argv[i], "PercentAllowed",
                                MAX(command_len, 1))) {
            /* overload percent_used here */
            if (get_uint16(argv[i]+end, &res->percent_used,
                           "PercentAllowed") == SLURM_SUCCESS) {
                set = 1;
            }
        } else if (!strncasecmp(argv[i], "Server",
                                MAX(command_len, 1))) {
            if (!res->server) {
                res->server=
                    strip_quotes(argv[i]+end, NULL, 1);
            }
            set = 1;
        } else if (!strncasecmp(argv[i], "Type",
                                MAX(command_len, 1))) {
            char *temp = strip_quotes(argv[i]+end, NULL, 1);

            if (!strncasecmp("License", temp,
                             MAX(strlen(temp), 1))) {
                res->type = SLURMDB_RESOURCE_LICENSE;
            } else {
                exit_code=1;
                fprintf(stderr,
                        " Unknown resource type: '%s'  "
                        "Valid resources is License.\n",
                        temp);
            }
        } else {
            exit_code = 1;
            printf(" Unknown option: %s\n"
                   " Use keyword 'where' to modify condition\n",
                   argv[i]);
        }
    }

    (*start) = i;

    return set;
}
uint16 HCICommandCompletePDU::get_op_code () const
{
    return get_uint16(3) ;
} 
Beispiel #27
0
uint16_t gme_game_get_bonus_entry_score(const struct gme_game* g) {
  assert(g->type==6);
  return get_uint16(g->raw+2);
}
Beispiel #28
0
static int
decode_data(double **data, const xmlChar * input, dataFormat data_format,
            codingTypes coding, byteOrder byte_order, int max_input_len)
{
    GArray *data_stream, *debase64_buf, *decoded_data;
    char *p, *end_ptr;
    unsigned int i;
    double val;
    int data_count = 0;

    gwy_debug("start.");

    if (input == NULL) {
        g_warning("SPML: decode_data(): NULL input");
        *data = NULL;
        return 0;
    }
    switch (coding) {
        case ZLIB_COMPR_BASE64:
            /*/ XXX: strlen() may not be nice there */
            if (decode_b64((char *)input, &debase64_buf, strlen(input)) != 0) {
                if (debase64_buf != NULL) {
                    g_array_free(debase64_buf, TRUE);
                }
                g_warning("Cannot decode data in BASE64 code.");
                *data = NULL;
                return 0;
            }
            if (inflate_dynamic_array(debase64_buf, &data_stream) != 0) {
                g_warning("Cannot inflate compressed data.");
                g_array_free(debase64_buf, TRUE);
                if (data_stream != NULL) {
                    g_array_free(data_stream, TRUE);
                }
                *data = NULL;
                return 0;
            }
            g_array_free(debase64_buf, TRUE);
            break;
        case BASE64:
            /*/ XXX: strlen() may not be nice there */
            if (decode_b64((char *)input, &data_stream, strlen(input)) != 0) {
                g_warning("Cannot decode data in BASE64 code.");
                if (data_stream != NULL) {
                    g_array_free(data_stream, TRUE);
                }
                *data = NULL;
                return 0;
            }
            break;
        case ASCII:
            p = (char *)input;
            data_stream = g_array_new(FALSE, FALSE, sizeof(double));
            while (p != NULL) {
                double num;

                if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') {
                    p++;
                    continue;
                }
                num = g_ascii_strtod(p, &end_ptr);
                if (num == 0 && end_ptr == p) {
                    g_warning("SPML: decode_data(): No conversion performed "
                              "from ASCII string.");
                    break;
                }
                g_array_append_val(data_stream, num);
                p = end_ptr;
                data_count++;
            }

            break;
            /*/ TODO: */
        case HEX:
        case BINARY:
            g_warning("SPML: decode_data(): Data coding 'HEX' and 'BINARY' "
                      "not supported.");
            break;
        case UNKNOWN_CODING:
            break;
    }
    if (coding == ASCII) {
        /* we have already decoded data */
        if (max_input_len != -1 && data_count != max_input_len) {
            /* not enough input data to fill array defined by length
             * max_input_len */
            g_warning("SPML: decode_data():\n"
                      "Input has not the same length as declared in "
                        "dimensions\n"
                      "(max:%d vs read:%d). Has the channel attribute\n"
                      "'channelReadMethodName'? The channel may be  one\n"
                      "dimensional data used for axis values but not as\n"
                      "a source of data for Gwyddion.",
                      max_input_len, data_count);
            g_array_free(data_stream, TRUE);
            *data = NULL;
            return 0;
        }
        else {
            *data = (double *)data_stream->data;
            /* we can free dynamic array, but not */
            g_array_free(data_stream, FALSE);
            /* containing data. */
            gwy_debug("Datacount: %d", data_count);
            return data_count;
        }
    }
    decoded_data = g_array_new(FALSE, FALSE, sizeof(double));
    p = data_stream->data;
    i = 0;
    switch (data_format) {
        case FLOAT32:
            while (i < data_stream->len) {
                val = get_float32(&p, byte_order);
                g_array_append_val(decoded_data, val);
                data_count++;
                i += sizeof(float);
            }
            break;
        case FLOAT64:
            while (i < data_stream->len) {
                val = get_float64(&p, byte_order);
                g_array_append_val(decoded_data, val);
                i += sizeof(double);
            }
            break;
        case INT8:
            while (i < data_stream->len) {
                val = get_int8(&p);
                g_array_append_val(decoded_data, val);
                i += sizeof(gint8);
            }
            break;
        case INT16:
            while (i < data_stream->len) {
                val = get_int16(&p, byte_order);
                g_array_append_val(decoded_data, val);
                i += sizeof(gint16);
            }
            break;
        case INT32:
            while (i < data_stream->len) {
                val = get_int32(&p, byte_order);
                g_array_append_val(decoded_data, val);
                i += sizeof(gint32);
            }
            break;
        case UINT32:
            while (i < data_stream->len) {
                val = get_uint32(&p, byte_order);
                g_array_append_val(decoded_data, val);
                i += sizeof(guint32);
            }
            break;
        case UINT8:
            while (i < data_stream->len) {
                val = get_uint8(&p);
                g_array_append_val(decoded_data, val);
                i += sizeof(guint8);
            }
            break;
        case UINT16:
            while (i < data_stream->len) {
                val = get_uint16(&p, byte_order);
                g_array_append_val(decoded_data, val);
                i += sizeof(guint16);
            }
            break;
        case STRING:
            g_warning
                ("SPML: decode_data(): Data format 'String' not supported.");
            break;
        case UNKNOWN_DATAFORMAT:
            g_warning("SPML: decode_data(): Unknown dataformat.");
            break;
    }
    g_array_free(data_stream, TRUE);
    data_count = decoded_data->len;
    if (max_input_len != -1 && data_count != max_input_len) {
        g_warning("SPML: decode_data():\n"
                  "Input has not the same length as declared in dimensions\n"
                  "(max:%d vs read:%d). Has the channel attribute\n"
                  "'channelReadMethodName'? The channel may be  one\n"
                  "dimensional data used for axis values but not as\n"
                  "a source of data for Gwyddion.", max_input_len, data_count);
        g_array_free(decoded_data, TRUE);
        *data = NULL;
        return 0;
    }
    *data = (double *)decoded_data->data;
    g_array_free(decoded_data, FALSE);  /* we can free dynamic array, but not */
    /* containing data. */
    gwy_debug("Datacount: %d", data_count);
    return data_count;

}
Beispiel #29
0
uint16_t gme_game_get_repeat_oid(const struct gme_game* g) {
  return get_uint16(gme_game_get_last_round_p(g)+2);
}
uint16 BNEP_LISTEN_REQ_T_PDU::get_ether_type() const
{
    return get_uint16 ( BNEP_LISTEN_REQ_T_ether_type );
}