static uint8_t *
_dns_question(DNS_Query *query, uint8_t *buf)
{
	uint8_t *buf_ptr = buf;

	DNS_PTR_Method *hooks = NULL;
	if(config.config.osc.mode == OSC_MODE_UDP)
		hooks = hooks_udp;
	else
		hooks = hooks_tcp;

	char *qname;
	buf_ptr = _unroll_qname(query, buf_ptr, &qname);

	DNS_Question *question =(DNS_Question *)buf_ptr;
	question->QTYPE = hton(question->QTYPE);
	question->QCLASS = hton(question->QCLASS);
	buf_ptr += sizeof(DNS_Question);

	// TODO answer as unicast
	//uint_fast8_t unicast = question->QCLASS & MDNS_CLASS_UNICAST;

	if( (question->QCLASS & 0x7fff) == MDNS_CLASS_INET) // check question class
	{
		// for IP mDNS lookup
		if(  (question->QTYPE == MDNS_TYPE_A)
			|| (question->QTYPE == MDNS_TYPE_AAAA)
			|| (question->QTYPE == MDNS_TYPE_ANY) )
		{
			// reply with current IP when there is a request for our name
			if(!strncmp(hook_self, qname, len_self))
			{
				uint8_t *head = BUF_O_OFFSET(buf_o_ptr);
				uint8_t *tail = head;

				tail = _serialize_query(tail, query->ID, MDNS_FLAGS_QR | MDNS_FLAGS_AA, 0, 1, 0, 0);
				//FIXME append negative response for IPv6 via NSEC record
				tail = _serialize_answer(tail, hook_self, MDNS_TYPE_A, MDNS_CLASS_FLUSH | MDNS_CLASS_INET, MDNS_TTL_75MIN, 4);

				memcpy(tail, config.comm.ip, 4);
				tail += 4;

				udp_send(config.mdns.socket.sock, BUF_O_BASE(buf_o_ptr), tail-head);
			}
		}

		// for mDNS reverse-lookup and for mDNS-SD(service discovery)
		if( (question->QTYPE == MDNS_TYPE_PTR) || (question->QTYPE == MDNS_TYPE_ANY) )
		{
			DNS_PTR_Method *hook;
			for(hook=hooks; hook->name; hook++)
				if(!strcmp(hook->name, qname)) // is there a hook with this qname registered?
					hook->cb(query);
		}
	}

	return buf_ptr;
}
Beispiel #2
0
bool mld_interface::send_mld_query(const in6_addr &addr, const std::set<in6_addr> &sources) {
	if (!sources.empty() && mif_mld_version >= 2) {
		mldv2_query *query = g_mrd->opktb->header<mldv2_query>();

		query->construct_query(addr, conf());

		query->nsrcs = hton((uint16_t)sources.size());

		in6_addr *addr = g_mrd->opktb->header<in6_addr>(sizeof(mldv2_query));

		for (std::set<in6_addr>::const_iterator i = sources.begin();
				i != sources.end(); ++i) {
			*addr = *i;
			addr++;
		}

		if (mld->send_icmp(owner(), in6addr_linkscope_allnodes,
				   (icmp6_hdr *)query, query->length())) {
			m_stats.counter(QueryCount, TX)++;
			mld->stats().counter(QueryCount, TX)++;
			return true;
		} else {
			/*m_stats.counter(FailedSendQueryCount)++;
			mld->stats().counter(FailedSendQueryCount)++;*/
			return false;
		}
	}

	return true;
}
Beispiel #3
0
Datei: arp.c Projekt: e7/analysis
int main(int argc, char *argv[])
{
    int rslt = 0;
    char x = 0x12;

    fprintf(stdout, "net endian? %s\n", is_net_endian() ? "yes" : "no");
    fprintf(stdout, "0x%08x : ", x);
    hton(&x, sizeof(x));
    fprintf(stdout, "0x%08x\n", x);
    fprintf(stdout, "sizeof eth_head_st: %d\n", sizeof(eth_head_st));
    fprintf(stdout, "sizeof arp_frame_st: %d\n", sizeof(arp_frame_st));
    fprintf(stdout, "sizeof arp_packet_st: %d\n", sizeof(arp_packet_st));

    do {
        byte_t smac[MAC_ADDR_LEN] = {
            //0x4E, 0x55, 0xBB, 0x27, 0x00, 0x08,
            0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA,
        };
        byte_t sip[IP_ADDR_LEN] = {
            //0x65, 0x38, 0xA8, 0xC0,
            0x01, 0x38, 0xA8, 0xC0,
        };
        byte_t dmac[MAC_ADDR_LEN] = {
            //0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
            0x4E, 0x55, 0xBB, 0x27, 0x00, 0x08,
        };
        byte_t dip[IP_ADDR_LEN] = {
            0x65, 0x38, 0xA8, 0xC0,
        };

        send_arp(dmac, dip, smac, sip);
    } while (0);

    return rslt;
}
Beispiel #4
0
bool
CC1101::begin(const void* config)
{
  // Reset the device
  m_cs.pulse(30);
  DELAY(30);
  strobe(SRES);
  DELAY(300);

  // Upload the configuration. Check for default configuration
  spi.begin(this);
  loop_until_bit_is_clear(PIN, Board::MISO);
  write_P(IOCFG2, 
	  config ? (const uint8_t*) config : CC1101::config, 
	  CONFIG_MAX);
  spi.end();

  // Adjust configuration with instance specific state
  uint16_t sync = hton(m_addr.network);
  spi.begin(this);
  loop_until_bit_is_clear(PIN, Board::MISO);
  write(PATABLE, 0x60);
  write(CHANNR, m_channel);
  write(ADDR, m_addr.device);
  write(SYNC1, &sync, sizeof(sync));
  spi.end();

  // Initiate device driver state and enable interrupt handler
  m_avail = false;
  spi.attach(this);
  m_irq.enable();
  return (true);
}
Beispiel #5
0
void serialize(OutputArchive& ar, boost::units::quantity<U, T> q)
{
    static_assert(std::is_integral<T>::value,
            "Only integral based quantities are supported");
    auto tmp = hton(q.value());
    ar << tmp;
}
Beispiel #6
0
void csismp_construct(
        unsigned char *buffer,
        unsigned char source_addr[6],
        unsigned char dest_addr[6],
        int c_type,
        int start,
        int end,
        int slice,
        int session,
        const char* s_tlvs,
        int len)
{
    struct packet *csismp = (void *)buffer;

    int i;
    memcpy(csismp->smac, source_addr, 6);
    memcpy(csismp->dmac, dest_addr, 6);
    csismp->pro_type = 0x1122;
    csismp->c_type = c_type;

    csismp->start = start;
    csismp->end = end;
    csismp->slice = slice;
    csismp->session = session;

    strncpy(csismp->tlvs, s_tlvs, len);
    hton((char *)csismp, 22 + len);

}
Beispiel #7
0
bool
RFM69::begin(const void* config)
{
  // Wait for the transceiver to become ready
  do write(SYNC_VALUE1, 0xaa); while (read(SYNC_VALUE1) != 0xaa);
  do write(SYNC_VALUE1, 0x55); while (read(SYNC_VALUE1) != 0x55);

  // Upload the configuration. Check for default configuration
  const uint8_t* cp = RFM69::config;
  Reg reg;
  if (config != NULL) cp = (const uint8_t*) config;
  while ((reg = (Reg) pgm_read_byte(cp++)) != 0)
    write(reg, pgm_read_byte(cp++));

  // Adjust configuration with instance specific state
  uint16_t sync = hton(m_addr.network);
  write(SYNC_VALUE1, &sync, sizeof(sync));
  write(NODE_ADDR, m_addr.device);

  // Set standby mode and calibrate RC oscillator
  recalibrate();

  // Initiate device driver state and enable interrupt handler
  m_avail = false;
  m_done = true;
  spi.attach(this);
  m_irq.enable();
  return (true);
}
Beispiel #8
0
void mldv2_query::construct(const in6_addr &addr, int type, mld_intfconf_node *n) {
    mldv1::construct(addr, type, n);

    qrv = n->robustness();
    suppress = 0;
    resv2 = 0;

    uint32_t qis = n->query_interval() / 1000;

    if (qis < 128)
        qqic = qis;
    else {
        int exp = 0;

        while ((qis >> (exp+3)) > 0x1f)
            exp++;

        qis >>= exp+3;
        qis -= 0x10;

        qqic = 0x80 | (exp << 4) | qis;
    }

    nsrcs = hton((uint16_t)0);
}
Beispiel #9
0
	static inline void compress(I begin,I end,O out)
	{
		unsigned int bufLen = LZ4_compressBound(ZT_COMPRESSION_BLOCK_SIZE);
		char *buf = new char[bufLen * 2];
		char *buf2 = buf + bufLen;

		try {
			I inp(begin);
			for(;;) {
				unsigned int readLen = 0;
				while ((readLen < ZT_COMPRESSION_BLOCK_SIZE)&&(inp != end)) {
					buf[readLen++] = (char)*inp;
					++inp;
				}
				if (!readLen)
					break;

				uint32_t l = hton((uint32_t)readLen);
				out((const void *)&l,4); // original size

				if (readLen < 32) { // don't bother compressing itty bitty blocks
					l = 0; // stored
					out((const void *)&l,4);
					out((const void *)buf,readLen);
					continue;
				}

				int lz4CompressedLen = LZ4_compressHC(buf,buf2,(int)readLen);
				if ((lz4CompressedLen <= 0)||(lz4CompressedLen >= (int)readLen)) {
					l = 0; // stored
					out((const void *)&l,4);
					out((const void *)buf,readLen);
					continue;
				}

				l = hton((uint32_t)lz4CompressedLen); // lz4 only
				out((const void *)&l,4);
				out((const void *)buf2,(unsigned int)lz4CompressedLen);
			}

			delete [] buf;
		} catch ( ... ) {
			delete [] buf;
			throw;
		}
	}
Beispiel #10
0
 prefixed_send_buffer(data_type&& data)
 : data_(std::move(data))
 , prefix_(hton(static_cast<prefix_type>(data_.size())))
 {
   BOOST_ASSERT_MSG(std::numeric_limits<prefix_type>::max() >= data_.size(),
     "prefixed_send_buffer: Try to send data which size is too large "
     "(choose a larger prefix type).");
 }
static uint8_t *
_dns_answer(DNS_Query *query, uint8_t *buf)
{
	uint8_t *buf_ptr = buf;

	char *qname;
	buf_ptr = _unroll_qname(query, buf_ptr, &qname);

	DNS_Answer *answer =(DNS_Answer *)buf_ptr;
	answer->RTYPE = hton(answer->RTYPE);
	answer->RCLASS = hton(answer->RCLASS);
	answer->TTL = htonl(answer->TTL);
	answer->RLEN = hton(answer->RLEN);
	buf_ptr += sizeof(DNS_Answer);

	switch(answer->RTYPE)
	{
		case MDNS_TYPE_A:
			// ignore when qname was not requested by us previously
			if(!resolve.cb || strcmp(qname, resolve.name))
				break;
		
			//TODO handle conflicts when probing

			uint8_t *ip = (uint8_t *)buf_ptr; 
			if(ip_part_of_subnet(ip)) // check IP for same subnet TODO make this configurable
			{
				timer_pause(mdns_timer); // stop timeout timer

				resolve.cb(ip, resolve.data);

				// reset request
				resolve.name[0] = '\0';
				resolve.cb = NULL;
				resolve.data = NULL;
			}
			break;
		default:
			// ignore remaining answer types, e.g MDNS_TYPE_PTR, MDNS_TYPE_SRV, MDNS_TYPE_TXT
			break;
	}

	buf_ptr += answer->RLEN; // skip rdata

	return buf_ptr;
}
static uint8_t *
_serialize_answer(uint8_t *buf, char *qname, uint16_t rtype, uint16_t rclass, uint32_t ttl, uint16_t rlen)
{
	uint16_t *len = NULL;
	uint8_t *buf_ptr = _serialize_answer_inline(buf, qname, rtype, rclass, ttl, &len);
	*len = hton(rlen);

	return buf_ptr;
}
static uint8_t *
_serialize_question(uint8_t *buf, char *qname, uint16_t qtype, uint16_t qclass)
{
	uint8_t *buf_ptr = buf;

	uint16_t len = strlen(qname) + 1;
	memcpy(buf_ptr, qname, len);
	buf_ptr += len;

	DNS_Question quest;
	quest.QTYPE = hton(qtype);
	quest.QCLASS = hton(qclass);

	memcpy(buf_ptr, &quest, sizeof(DNS_Question));
	buf_ptr += sizeof(DNS_Question);

	return buf_ptr;
}
Beispiel #14
0
void mldv1::construct(const in6_addr &addr, int _type, mld_intfconf_node *n) {
    type = _type;
    code = 0;
    checksum = 0;

    /* General Query
     *   max_response_delay = [Query Response Interval]
     * Multicast-Address-Specific Query
     *   max_response_delay = [Last Listener Query Interval] */

    if (IN6_IS_ADDR_UNSPECIFIED(&addr))
        maxdelay = hton((uint16_t)n->query_response_interval());
    else
        maxdelay = hton((uint16_t)n->last_listener_query_interval());

    data = hton((uint16_t)0);

    mcaddr = addr;
}
static uint8_t *
_serialize_answer_inline(uint8_t *buf, char *qname, uint16_t rtype, uint16_t rclass, uint32_t ttl, uint16_t **rlen)
{
	uint8_t *buf_ptr = buf;

	uint16_t len = strlen(qname) + 1;
	memcpy(buf_ptr, qname, len);
	buf_ptr += len;

	DNS_Answer a;
	a.RTYPE = hton(rtype);
	a.RCLASS = hton(rclass);
	a.TTL = htonl(ttl);
	a.RLEN = 0;
	
	*rlen = (uint16_t *)(buf_ptr + offsetof(DNS_Answer, RLEN));

	memcpy(buf_ptr, &a, sizeof(DNS_Answer));
	buf_ptr += sizeof(DNS_Answer);

	return buf_ptr;
}
/*
 * Creates a streaming socket and connects to a server.
 *
 * serverName - the ip address or hostname of the server given as a string
 * port       - the port number of the server
 * dest       - the server's address information; the structure should be created with information
 *              on the server (like port, address, and family) in this function call
 *
 * return value - the socket identifier or a negative number indicating the error if a connection could not be established
 */
int createSocket(char * serverName, int port, struct sockaddr_in * dest)
{
		int socketCreation = 0;
		memset(dest, 0, sizeof(dest));
		dest.sin_family = AF_INET;
		inet_pton(AF_INET, serverName, dest.sin_addr); //Sever IP address
		dest.sin_port = hton(port);
		socketCreation = socket(PF_INET, SOCK_STREAM, 0);
		if(connect(s, (struct sockaddr *)dest, sizeof(dest))< 0)
		{
			socketCreation = -1;
		}
		return socketCreation;
}
int LocalSocketStream::send(const Head & head, const void * buf, unsigned int size)
{
	if (fd < 0) return -1;
	if (!buf) return -1;
	if (size == 0) return -1;

	Head clone_head(head);
	uint8_t buf_head[sizeof(head)];
	hton(clone_head);
	serialize(buf_head, clone_head);

	int rc = ::write(fd, buf_head, sizeof(buf_head));
	if (rc < 0) return -1;

	rc = ::write(fd, buf, size);
	if (rc < 0) return -1;
	return rc;
}
Beispiel #18
0
bool SendFile( SOCKET sock, const char* strFileName, int nBufSize )
{
	//get file header
	NETF_STAT nfstat;
	if( GetNetfStat(strFileName, &nfstat)!=0 )return false;

	//send file header
	hton( nfstat );
	SendNetfStat( sock, &nfstat );

	//send the file content stream.
	FILE* pf = fopen( strFileName, "rb" );
	if( pf==NULL )return false;

	bool bOk = SendFileStream( sock, pf, nBufSize );

	fclose( pf );
	return bOk;
}
Beispiel #19
0
int htoi(char s[])
{
	int len, i, n;
	len = strlen(s);
	n = 0;
	if (len < 3)
 		return -1;
	if (s[0] != '0')
		return -1;
	if (s[1] != 'x' && s[1] != 'X')
		return -1;
	for (i = 2; i < len; ++i) {
		if ((s[i] >= '0' && s[i] <= '9') || (s[i] >='a' && s[i] <= 'z') || (s[i] >= 'A' && s[i]<= 'Z')) {
			n = 16 * n + hton(s[i]);
		} else {
			return -1;
		}
	}
	return n;
}
void 
mdns_dispatch(uint8_t *buf, uint16_t len)
{
	(void)len;
	// update qname labels corresponding to self
	len_self = _update_hook_self(config.name);
	len_instance = _update_hook_instance(config.name);
	len_arpa = _update_hook_arpa(config.comm.ip);

	uint8_t *buf_ptr = buf;
	DNS_Query *query =(DNS_Query *)buf_ptr;

	// convert from network byteorder
	query->ID = hton(query->ID);
	query->FLAGS = hton(query->FLAGS);
	query->QDCOUNT = hton(query->QDCOUNT);
	query->ANCOUNT = hton(query->ANCOUNT);
	query->NSCOUNT = hton(query->NSCOUNT);
	query->ARCOUNT = hton(query->ARCOUNT);

	uint8_t qr =(query->FLAGS & MDNS_FLAGS_QR) >> MDNS_FLAGS_QR_BIT;
	//uint8_t opcode =(query->FLAGS & MDNS_FLAGS_OPCODE) >> MDNS_FLAGS_OPCODE_SHIFT;
	//uint8_t aa =(query->FLAGS & MDNS_FLAGS_AA) >> MDNS_FLAGS_AA_BIT;
	//uint8_t tc =(query->FLAGS & MDNS_FLAGS_TC) >> MDNS_FLAGS_TC_BIT;
	//uint8_t rd =(query->FLAGS & MDNS_FLAGS_RD) >> MDNS_FLAGS_RD_BIT;
	//uint8_t ra =(query->FLAGS & MDNS_FLAGS_RA) >> MDNS_FLAGS_RA_BIT;
	//uint8_t z =(query->FLAGS & MDNS_FLAGS_Z) >> MDNS_FLAGS_Z_SHIFT;
	//uint8_t rcode =(query->FLAGS & MDNS_FLAGS_RCODE) >> MDNS_FLAGS_RCODE_SHIFT;

	buf_ptr += sizeof(DNS_Query);

	uint_fast8_t i;
	switch(qr)
	{
		case 0x0: // mDNS Query Question
			for(i=0; i<query->QDCOUNT; i++) // walk all questions
				buf_ptr = _dns_question(query, buf_ptr);

			// ignore answers
			break;
		case 0x1: // mDNS Query Answer
			for(i=0; i<query->QDCOUNT; i++) // skip all questions
				buf_ptr += strlen((char *)buf_ptr) + 1 + sizeof(DNS_Question);

			for(i=0; i<query->ANCOUNT; i++) // walk all answers
				buf_ptr = _dns_answer(query, buf_ptr);
			break;
	}
}
Beispiel #21
0
int
ICMP::ping_request(uint8_t dest[4])
{
  // Check given socket
  if (m_sock == NULL) return (ENOTSOCK);

  // Build echo request block
  header_t req;
  req.type = ECHO;
  req.code = 0;
  req.checksum = 0;
  req.echo.id = m_id;
  req.echo.seq = ++m_seq;
  req.timestamp = RTC::millis();
  req.checksum = hton(INET::checksum(&req, sizeof(req)));

  // And send to destination network address
  int res = m_sock->send(&req, sizeof(req), dest, 0);
  if (res < 0) return (res);
  return (res == sizeof(req) ? 0 : -1);
}
Beispiel #22
0
std::vector<u8> AmfVector<T, typename VectorProperties<T>::type>::serialize(SerializationContext& ctx) const {
	int index = ctx.getIndex(*this);
	if (index != -1)
		return std::vector<u8> { VectorProperties<T>::marker, u8(index << 1) };
	ctx.addObject(*this);

	// U29V value
	std::vector<u8> buf = AmfInteger::asLength(values.size(),
		VectorProperties<T>::marker);

	// fixed-vector marker
	buf.push_back(fixed ? 0x01 : 0x00);

	for (const T& it : values) {
		// values are encoded in network byte order
		// ints are encoded as U32, not U29
		T netvalue = hton(it);
		const u8* bytes = reinterpret_cast<const u8*>(&netvalue);
		buf.insert(buf.end(), bytes, bytes + VectorProperties<T>::size);
	}

	return buf;
}
static uint8_t *
_serialize_TXT_instance(uint8_t *buf, uint16_t rclass, uint32_t ttl)
{
	uint8_t *buf_ptr = buf;
	uint16_t *len = NULL;

	DNS_PTR_Method *hooks = NULL;
	if(config.config.osc.mode == OSC_MODE_UDP)
		hooks = hooks_udp;
	else
		hooks = hooks_tcp;

	buf_ptr = _serialize_answer_inline(buf_ptr, hooks[HOOK_INSTANCE].name, MDNS_TYPE_TXT, rclass, ttl, &len);

	uint8_t *txt = buf_ptr;
	buf_ptr = _serialize_TXT_record(buf_ptr, TXT_TXTVERSION);
	buf_ptr = _serialize_TXT_record(buf_ptr, TXT_VERSION);
	buf_ptr = _serialize_TXT_record(buf_ptr, TXT_URI);
	buf_ptr = _serialize_TXT_record(buf_ptr, TXT_TYPES);
	if(config.config.osc.mode == OSC_MODE_SLIP)
		buf_ptr = _serialize_TXT_record(buf_ptr, TXT_FRAMING);
	buf_ptr = _serialize_TXT_record(buf_ptr, TXT_RESET[reset_mode]);
	if(config.dhcpc.enabled || config.ipv4ll.enabled)
	{
		if(config.dhcpc.enabled)
			buf_ptr = _serialize_TXT_record(buf_ptr, TXT_DHCP);
		if(config.ipv4ll.enabled)
			buf_ptr = _serialize_TXT_record(buf_ptr, TXT_IPV4LL);
	}
	else
		buf_ptr = _serialize_TXT_record(buf_ptr, TXT_STATIC);
	//TODO send UID?

	*len = hton(buf_ptr - txt);

	return buf_ptr;
}
static uint8_t *
_serialize_query(uint8_t *buf, uint16_t id, uint16_t flags, uint16_t qdcount, uint16_t ancount, uint16_t nscount, uint16_t arcount)
{
	uint8_t *buf_ptr = buf;

	DNS_Query q;
	q.ID = hton(id);
	q.FLAGS = hton(flags);
	q.QDCOUNT = hton(qdcount); // number of questions
	q.ANCOUNT = hton(ancount); // number of answers
	q.NSCOUNT = hton(nscount); // number of authoritative records
	q.ARCOUNT = hton(arcount); // number of resource records

	memcpy(buf_ptr, &q, sizeof(DNS_Query));
	buf_ptr += sizeof(DNS_Query);

	return buf_ptr;
}
Beispiel #25
0
char * tftp_get(IPAddr server, char * file,
		void(*receiver)(Octet *, Uint32)) {
  UDP *sendBuf = (UDP *)enet_alloc();
  UDPPort local = udp_allocPort(NULL);
  sendBuf->ip.dest = hton(server);
  sendBuf->udp.dest = htons(tftpPort);
  sendBuf->udp.srce = htons(local);
  TFTPHeader * sendHeader = (TFTPHeader *)&(sendBuf->data[0]);
  sendHeader->op = htons(tftpOpRRQ);
  Uint32 pos = tftpPosName;
  appendStr(sendBuf, &pos, file);
  appendStr(sendBuf, &pos, "octet");
  Uint32 blockNum;
  for (blockNum = 1; ; blockNum++) {
    Uint32 recvLen;
    IP * recvBuf;
    TFTPHeader * recvHeader;
    Octet * recvData;
    Uint32 dataLen;
    int tries;
    for (tries = 0; ; tries++) {
      if (tries >= retryLimit) {
	udp_freePort(local);
	enet_free((Enet *)sendBuf);
	return "Timeout";
      }
      udp_send(sendBuf, pos);
      recvLen = udp_recv(&recvBuf, local, timeout);
      if (recvBuf) {
	recvHeader = (TFTPHeader *)udp_payload(recvBuf);
	recvData = udp_payload(recvBuf) + tftpPosData;
	dataLen = recvLen - tftpPosData;
	if (ntohs(recvHeader->op) == tftpOpData) {
	  if (ntohs(recvHeader->block) == blockNum) break;
	} else if (ntohs(recvHeader->op) == tftpOpError) {
	  recvData[dataLen-1] = 0; // in case server omitted it
	  udp_freePort(local);
	  enet_free((Enet *)sendBuf);
	  int slen = strlen((char *)recvData);
	  char *s = malloc(slen+1);
	  strncpy(s, (char *)recvData, slen+1);
	  udp_recvDone(recvBuf);
	  return s;
	} else {
	  udp_freePort(local);
	  enet_free((Enet *)sendBuf);
	  udp_recvDone(recvBuf);
	  return "Unknown opcode from server";
	}
	// ignore other stuff - excess retransmissions
	udp_recvDone(recvBuf);
      }
    }
    // The only way to get here is by receiving the expected data block
    receiver(recvData, dataLen);
    UDPHeader *recvUDPHeader = (UDPHeader *)ip_payload(recvBuf);
    sendBuf->udp.dest = recvUDPHeader->srce;
    sendHeader->op = htons(tftpOpAck);
    sendHeader->block = recvHeader->block;
    pos = tftpPosData;
    udp_recvDone(recvBuf);
    if (dataLen < 512) break;
  }
  udp_send(sendBuf, pos); // final ACK, sent without retransmissions
  udp_freePort(local);
  enet_free((Enet *)sendBuf);
  return NULL;
}
Beispiel #26
0
void 
hton(int16_t  val, uint8_t* bytes)
{
	hton((uint16_t)val, bytes);		
}
Beispiel #27
0
bool 
Babuino::withInt32()
{
	STACKPTR location, index;
	int32_t  rhs, lhs;

	switch (_regs.opCode)
	{
	case OP_ASHIFT:
	case OP_LSHIFT:
		{
			int8_t shift;
			popUint8(_stack, (uint8_t*)&shift);
			popUint32(_stack, (uint32_t*)&lhs);
			if (shift >= 0)
				pushUint32(_stack, (uint32_t)(lhs << shift));
			else
				pushUint32(_stack, (uint32_t)(lhs >> -shift));
			return true;
		}
	case OP_SET:
		//Serial.println("---set---");

		popStackPtr(_stack, &location);
		popUint32(_stack, (uint32_t*)&rhs);

		setUint32(_stack, location, (uint32_t)rhs);
		return true;

	case OP_GET:
		//Serial.println("---get---");
		popStackPtr(_stack, &location);
		getUint32(_stack, location, (uint32_t*)&rhs);
		pushUint32(_stack, (uint32_t)rhs);
		return true;

	case OP_ASET:
		//Serial.println("---aset---");
		popStackPtr(_stack, &location);
		popStackPtr(_stack, &index);
		popUint32(_stack, (uint32_t*)&rhs);
		setUint32(_stack, location + index * sizeof(int32_t), (uint32_t)rhs);
		return true;

	case OP_AGET:
		//Serial.println("---aget---");
		popStackPtr(_stack, &location);
		popStackPtr(_stack, &index);
		getUint32(_stack, location + index * sizeof(int32_t), (uint32_t*)&rhs);
		pushUint32(_stack, (uint32_t)rhs);
		return true;

	case OP_OUTPUT:
		{
			//Serial.print("output ");
			popUint32(_stack, (uint32_t*)&rhs);	// The return value
				// point to where the arguments size is on the stack.
			location = getArgsLocation();
			uint8_t argsSize;
			getUint8(_stack, location - sizeof(uint8_t), &argsSize); // Get size of args. 
				// If the size > 0 then step over the size location too. 
				// Otherwise keep pointing to the same place because the return
				// value should overwrite where the arguments size would be. 
			if (argsSize > 0)
				argsSize += sizeof(uint8_t);
			setUint32(_stack, location - (STACKPTR)argsSize - sizeof(int32_t), (uint32_t)rhs);
		}
		return true;

	case OP_SEND:
		{
			//Serial.println("---send---");
			popUint32(_stack, (uint32_t*)&rhs);
			uint8_t buf[sizeof(int32_t)];
			hton(rhs, buf);
			//_defaultStream->write(nbuf, sizeof(int32_t)); // Replaced for debugging
			_defaultStream->print(rhs);
		}
		return true;

	case OP_SENDN:
		{
			//Serial.println("---sendn---");
			uint8_t items;
			uint8_t port;
			STACKPTR bufLoc;
			popUint8(_stack, &items);
			popUint8(_stack, &port);
			popStackPtr(_stack, &bufLoc); 
			int32_t* buf = (int32_t*)getStackAddress(_stack, bufLoc);
			uint8_t nbuf[sizeof(int32_t)];
			for (int i = 0; i < items; i++)
			{
				rhs = *buf;
				hton(rhs, nbuf);
				//_defaultStream->write(nbuf, sizeof(int32_t)); // Replaced for debugging
				_defaultStream->print(rhs);
				buf++;
			}
		}
		return true;
#ifdef SUPPORT_STRING
	case OP_TOSTR:
		{
			//Serial.println("---tostr---");
			popUint32(_stack, (uint32_t*)&rhs);
				// ***KLUDGE WARNING***
				// Borrowing unused (hopefully) stack space as a buffer!
				// just to avoid having to allocate another buffer.
			
			char* psz = (char *)getTopAddress(_stack);
			itoa((int) rhs, psz, 10);
				// Logically this is wrong because I'm apparently 
				// pushing a string to a location that it already 
				// occupies. However, the stack implementation 
				// pushes strings onto a separate stack, then
				// pushes the location onto the main stack. So
				// the string doesn't get copied over itself, and
				// is already copied before the first characters are
				// overwritten by pushing the said location onto the
				// main stack.
			pushString(_stack, (uint8_t*)psz);
		}
		return true;
#endif
	case OP_FOREACH:
		{	
			//Serial.print("foreach ");
			PROGPTR blockAddr;
			popProgPtr(_stack, &blockAddr);		// Block address
			popStackPtr(_stack, &location);			// Iterator variable location (Variable contains a 'pointer')
			uint8_t itemsRemaining;
			popUint8(_stack, &itemsRemaining);			// Number of items remaining
				// If we've gone through the block then we need to pop the
				// previous list item off the stack
			if (hasBlockExecuted())
			{
				uint32_t tmpUint32;
				popUint32(_stack, &tmpUint32);
			}

			if (itemsRemaining > 0)				// Any items remaining
			{
					// Set the value of the variable to the location on the
					// stack of the next list item (ie the top)
				setStackPtr(_stack, location, getTop(_stack) - sizeof(int32_t));
				_regs.pc = blockAddr;	// Point to the top of the block for the next iteration
				itemsRemaining--;					// Decrement the number of items remaining
				pushUint8(_stack, itemsRemaining);		// Save number of items remaining for next time
				pushStackPtr(_stack, location);		// Save iterator variable location for next time
				pushProgPtr(_stack, blockAddr);	// Save block address for next time
			}
			else
			{
				ascendBlock();			// Leaving. Pop the block.
			}
		}
		return true;
	}

	popUint32(_stack, (uint32_t*)&rhs);

	switch (_regs.opCode)
	{
	case OP_BITNOT:
		pushUint32(_stack, (uint32_t)~rhs);
		return true;

	case OP_ABS:
		pushUint32(_stack, (uint32_t)abs(rhs));
		return true;

	case OP_NEG:
		pushUint32(_stack, (uint32_t)-rhs);
		return true;
	}

	popUint32(_stack, (uint32_t*)&lhs);

	switch (_regs.opCode)
	{
	case OP_ADD:
		pushUint32(_stack, (uint32_t)(lhs + rhs));
		return true;

	case OP_SUB:
		pushUint32(_stack, (uint32_t)(lhs - rhs));
		return true;

	case OP_MUL:
		pushUint32(_stack, (uint32_t)(lhs * rhs));
		return true;

	case OP_DIV:
		pushUint32(_stack, (uint32_t)(lhs / rhs));
		return true;

	case OP_MOD:
		pushUint32(_stack, (uint32_t)(lhs % rhs));
		return true;

	case OP_EQ:
		pushUint8(_stack, (uint8_t)(lhs == rhs));
		return true;


	case OP_GT:
		pushUint8(_stack, (uint8_t)(lhs > rhs));
		return true;

	case OP_LT:
		pushUint8(_stack, (uint8_t)(lhs < rhs));
		return true;

	case OP_LE:
		pushUint8(_stack, (uint8_t)(lhs <= rhs));
		return true;

	case OP_GE:
		pushUint8(_stack, (uint8_t)(lhs >= rhs));
		return true;

	case OP_NE:
		pushUint8(_stack, (uint8_t)(lhs != rhs));
		return true;

	case OP_BITAND:
		pushUint32(_stack, (uint32_t)(lhs & rhs));
		return true;

	case OP_BITOR:
		pushUint32(_stack, (uint32_t)(lhs | rhs));
		return true;

	case OP_BITXOR:
		pushUint32(_stack, (uint32_t)(lhs ^ rhs));
		return true;
	
	case OP_MIN:
		pushUint32(_stack, (uint32_t)min(lhs, rhs));
		return true;	
	case OP_MAX:
		pushUint32(_stack, (uint32_t)max(lhs, rhs));
		return true;
	}
	return false;
}
Beispiel #28
0
 operator network_type() const { return network_cast(hton(BASE::get())); }
Beispiel #29
0
static void serialize_value(lua_State *L, int pos, luaL_Buffer* frame, int* indice, uint16_t* key) {
    if (!lua_checkstack(L, 2)) {
        luaL_error(L, "cannot serialize: stack won't grow");
    }
    uint8_t type = get_luatobin_type(L, pos);
    switch (type) {
    case BIN_NIL: {
        //printf("(nil[1])");
        lua_pushlstring(L, (char *) &type, 1);
        write_object(L, indice);
        break;
    }

    case BIN_BOOLEAN: {
        //printf("(boolean[2])");
        int boolean = lua_toboolean(L, pos);
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        luaL_addchar(frame, boolean & 0xFF);
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_DOUBLE: {
        double number = lua_tonumber(L, pos);
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        //printf("(number[%d])", sizeof(number));
        if (sendian.double_) hton(&number, sizeof(number), sendian.double_);
        luaL_addlstring(frame, (char*) &number, sizeof(number));
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_INTEGER: {
        int32_t number = lua_tointeger(L, pos);
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        //printf("(number[%d])", sizeof(number));
        if (sendian.int32_) hton(&number, sizeof(number), sendian.int32_);
        luaL_addlstring(frame, (char*) &number, sizeof(number));
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_STRING: {
        uint16_t cached = verify_cache(L, pos, key);
        if (cached != 0) {
            //printf("(stringref[%d])", cached);
            luaL_buffinit(L, frame);
            luaL_addchar(frame, BIN_REF);
            if (sendian.int16_) hton(&cached, sizeof(cached), sendian.int16_);
            luaL_addlstring(frame, (char*) &cached, sizeof(cached));
            luaL_pushresult(frame);
            write_object(L, indice);
            break;
        }
        size_t s;
        const char* string = lua_tolstring(L, pos, &s);
        if (s >= 0xFFFF)
            luaL_error(L, "cannot serialize: string length > 65k");
        uint16_t size = (uint16_t) s;
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        uint16_t nsize = size;
        if (sendian.int16_) hton(&nsize, sizeof(nsize), sendian.int16_);
        luaL_addlstring(frame, (char*) &nsize, sizeof(nsize));
        //printf("(string[%d][%d])", *key, size);
        luaL_addlstring(frame, string, size);
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_FUNCTION: {
        uint16_t cached = verify_cache(L, pos, key);
        if (cached != 0) {
            //printf("(functionref[%d])", cached);
            luaL_buffinit(L, frame);
            luaL_addchar(frame, BIN_REF);
            if (sendian.int16_) hton(&cached, sizeof(cached), sendian.int16_);
            luaL_addlstring(frame, (char*) &cached, sizeof(cached));
            luaL_pushresult(frame);
            write_object(L, indice);
            break;
        }
        serialize_function(L, frame, pos);
        size_t s;
        const char* string = lua_tolstring(L, -1, &s);
        if (s >= 0xFFFF)
            luaL_error(L, "cannot serialize: function length > 65k");
        uint16_t size = (uint16_t) s;
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        uint16_t nsize = size;
        if (sendian.int16_) hton(&nsize, sizeof(nsize), sendian.int16_);
        luaL_addlstring(frame, (char*) &nsize, sizeof(nsize));
        //printf("(function[%d][%d])", *key, size);
        luaL_addlstring(frame, string, size);
        luaL_pushresult(frame);
        write_object(L, indice);
        lua_pop(L, 1); // remove the serialized function
        break;
    }

    case BIN_TABLE: {
        uint16_t cached = verify_cache(L, pos, key);
        if (cached != 0) {
            //printf("(tableref[%d])", cached);
            luaL_buffinit(L, frame);
            luaL_addchar(frame, BIN_REF);
            if (sendian.int16_) hton(&cached, sizeof(cached), sendian.int16_);
            luaL_addlstring(frame, (char*) &cached, sizeof(cached));
            luaL_pushresult(frame);
            write_object(L, indice);
            break;
        }
        // reserved for table header (as size cannot be calculated beforehand)
        *indice = *indice + 1;
        int header = *indice;
        //printf("{table=");
        int top;
        size_t s = 0;
        lua_pushnil(L);
        while (lua_next(L, pos) != 0) {
            top = lua_gettop(L);
            serialize_value(L, top - 1, frame, indice, key);
            serialize_value(L, top, frame, indice, key);
            lua_pop(L, 1);
            s++;
        }
        if (s >= 0xFFFF)
            luaL_error(L, "cannot serialize: table length > 65k");
        uint16_t size = (uint16_t) s;
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        uint16_t nsize = size;
        if (sendian.int16_) hton(&nsize, sizeof(nsize), sendian.int16_);
        luaL_addlstring(frame, (char*) &nsize, sizeof(nsize));
        luaL_pushresult(frame);
        // set table header
        lua_rawseti(L, 3, header);
        //printf("[%d]}", size);
        break;
    }

    default:
        luaL_error(L, "cannot serialize: unsupported type (%d)", lua_type(L, pos));
    }
}
Beispiel #30
0
Datei: arp.c Projekt: e7/analysis
// send_arp
// 功能:发送arp包
int send_arp(byte_t dmac[],
             byte_t dip[],
             byte_t smac[],
             byte_t sip[])
{
    static byte_t const ETH_FRAME_TYPE[] = {
        0x06, 0x08,
    };
    static byte_t const ARP_HD_TYPE[] = {
        0x01, 0x00,
    };
    static byte_t const ARP_PROTO_TYPE[] = {
        0x00, 0x08,
    };
    static byte_t const ARP_OP_TYPE[] = {
        ARPOP_REQUEST & 0xFF,
        (ARPOP_REQUEST >> 8) & 0xFF,
    };
    int rslt = 0;
    int fd = 0;
    arp_packet_st arp_packet = {
        {
            {0},
        },
        {
            {0},
        },
    };

    assert(NULL != dmac);
    assert(NULL != dip);
    assert(NULL != smac);
    assert(NULL != sip);

    // 创建套接字
    fd = socket(AF_INET, SOCK_PACKET, htons(ETH_P_ARP));
    if (-1 == fd) {
        perror("[ERROR] socket error");
        rslt = -1;
        goto SOCKET_ERR;
    }

    // arp包结构初始化,以太头
    memcpy(arp_packet.m_eth_head.ma_dest_mac, dmac, MAC_ADDR_LEN);
    hton(arp_packet.m_eth_head.ma_dest_mac, MAC_ADDR_LEN);
    memcpy(arp_packet.m_eth_head.ma_src_mac, smac, MAC_ADDR_LEN);
    hton(arp_packet.m_eth_head.ma_src_mac, MAC_ADDR_LEN);
    memcpy(arp_packet.m_eth_head.ma_frame_type,
           &ETH_FRAME_TYPE, ETH_FRAME_TYPE_LEN);
    hton(arp_packet.m_eth_head.ma_frame_type, ETH_FRAME_TYPE_LEN);

    // arp包结构初始化,arp帧
    memcpy(arp_packet.m_arp_frame.ma_hd_type, ARP_HD_TYPE, ARP_HD_TYPE_LEN);
    hton(arp_packet.m_arp_frame.ma_hd_type, ARP_HD_TYPE_LEN);

    memcpy(arp_packet.m_arp_frame.ma_proto_type,
           ARP_PROTO_TYPE, ARP_PROTO_TYPE_LEN);
    hton(arp_packet.m_arp_frame.ma_proto_type, ARP_HD_TYPE_LEN);

    arp_packet.m_arp_frame.m_hd_addr_len = MAC_ADDR_LEN;
    arp_packet.m_arp_frame.m_proto_addr_len = IP_ADDR_LEN;

    memcpy(arp_packet.m_arp_frame.ma_op_type, ARP_OP_TYPE, ARP_OP_TYPE_LEN);
    hton(arp_packet.m_arp_frame.ma_op_type, ARP_OP_TYPE_LEN);

    memcpy(arp_packet.m_arp_frame.ma_from_mac, smac, MAC_ADDR_LEN);
    hton(arp_packet.m_arp_frame.ma_from_mac, MAC_ADDR_LEN);
    memcpy(arp_packet.m_arp_frame.ma_from_ip, sip, IP_ADDR_LEN);
    hton(arp_packet.m_arp_frame.ma_from_ip, IP_ADDR_LEN);

    memcpy(arp_packet.m_arp_frame.ma_to_mac, dmac, MAC_ADDR_LEN);
    hton(arp_packet.m_arp_frame.ma_to_mac, MAC_ADDR_LEN);
    memcpy(arp_packet.m_arp_frame.ma_to_ip, dip, IP_ADDR_LEN);
    hton(arp_packet.m_arp_frame.ma_to_ip, IP_ADDR_LEN);

    while (1) {
        struct sockaddr target;
        int n = 0;

        strcpy(target.sa_data, "vboxnet0");
        n = sendto(fd, &arp_packet, sizeof(arp_packet_st), 0,
                       (struct sockaddr *)&target, sizeof(target));

        if (-1 == n) {
            fprintf(stderr, "[%d]", errno);
            fprintf(stderr, "[%d]", ENOTCONN);
            perror("[ERROR] sendto failed");
            rslt = -1;
            break;
        }

        sleep(1);
    }

    // 错误处理
    do {
        close(fd);
    SOCKET_ERR:
        break;
    } while (0);

    return rslt;
}