Example #1
1
/*
 * Convert a quota file from one format to another.
 */
int
quota_convert(struct quotafile *qf, int wordsize)
{
	struct quotafile *newqf;
	struct dqhdr64 dqh;
	struct dqblk dqblk;
	struct group *grp;
	int serrno, maxid, id, fd;

	/*
	 * Quotas must not be active and quotafile must be open
	 * for reading and writing.
	 */
	if ((qf->accmode & O_RDWR) != O_RDWR || qf->fd == -1) {
		errno = EBADF;
		return (-1);
	}
	if ((wordsize != 32 && wordsize != 64) ||
	     wordsize == qf->wordsize) {
		errno = EINVAL;
		return (-1);
	}
	maxid = quota_maxid(qf);
	if ((newqf = calloc(1, sizeof(*qf))) == NULL) {
		errno = ENOMEM;
		return (-1);
	}
	*newqf = *qf;
	snprintf(newqf->qfname, MAXPATHLEN + 1, "%s_%d.orig", qf->qfname,
	    qf->wordsize);
	if (rename(qf->qfname, newqf->qfname) < 0) {
		free(newqf);
		return (-1);
	}
	if ((newqf->fd = open(qf->qfname, O_RDWR|O_CREAT|O_TRUNC, 0)) < 0) {
		serrno = errno;
		goto error;
	}
	newqf->wordsize = wordsize;
	if (wordsize == 64) {
		memset(&dqh, 0, sizeof(dqh));
		memcpy(dqh.dqh_magic, Q_DQHDR64_MAGIC, sizeof(dqh.dqh_magic));
		dqh.dqh_version = htobe32(Q_DQHDR64_VERSION);
		dqh.dqh_hdrlen = htobe32(sizeof(struct dqhdr64));
		dqh.dqh_reclen = htobe32(sizeof(struct dqblk64));
		if (write(newqf->fd, &dqh, sizeof(dqh)) != sizeof(dqh)) {
			serrno = errno;
			goto error;
		}
	}
	grp = getgrnam(QUOTAGROUP);
	fchown(newqf->fd, 0, grp ? grp->gr_gid : 0);
	fchmod(newqf->fd, 0640);
	for (id = 0; id <= maxid; id++) {
		if ((quota_read(qf, &dqblk, id)) < 0)
			break;
		switch (newqf->wordsize) {
		case 32:
			if ((quota_write32(newqf, &dqblk, id)) < 0)
				break;
			continue;
		case 64:
			if ((quota_write64(newqf, &dqblk, id)) < 0)
				break;
			continue;
		default:
			errno = EINVAL;
			break;
		}
	}
	if (id < maxid) {
		serrno = errno;
		goto error;
	}
	/*
	 * Update the passed in quotafile to reference the new file
	 * of the converted format size.
	 */
	fd = qf->fd;
	qf->fd = newqf->fd;
	newqf->fd = fd;
	qf->wordsize = newqf->wordsize;
	quota_close(newqf);
	return (0);
error:
	/* put back the original file */
	(void) rename(newqf->qfname, qf->qfname);
	quota_close(newqf);
	errno = serrno;
	return (-1);
}
Example #2
0
UInt32 ByteOrder::hton32(UInt32 data)
{
   return htobe32(data);
}
Example #3
0
	I2NPMessage * CreateDatabaseLookupMsg (const uint8_t * key, const uint8_t * from, 
		uint32_t replyTunnelID, bool exploratory, std::set<i2p::data::IdentHash> * excludedPeers,
	    bool encryption, i2p::tunnel::TunnelPool * pool)
	{
		I2NPMessage * m = NewI2NPMessage ();
		uint8_t * buf = m->GetPayload ();
		memcpy (buf, key, 32); // key
		buf += 32;
		memcpy (buf, from, 32); // from
		buf += 32;
		if (replyTunnelID)
		{
			*buf = encryption ? 0x03: 0x01; // set delivery flag
			*(uint32_t *)(buf+1) = htobe32 (replyTunnelID);
			buf += 5;
		}
		else
		{	
			encryption = false; // encryption can we set for tunnels only
			*buf = 0; // flag
			buf++;
		}	
		
		if (exploratory)
		{
			*(uint16_t *)buf = htobe16 (1); // one exlude record
			buf += 2;
			// reply with non-floodfill routers only
			memset (buf, 0, 32);
			buf += 32;
		}
		else
		{
			if (excludedPeers)
			{
				int cnt = excludedPeers->size ();
				*(uint16_t *)buf = htobe16 (cnt);
				buf += 2;
				for (auto& it: *excludedPeers)
				{
					memcpy (buf, it, 32);
					buf += 32;
				}	
			}
			else
			{	
				// nothing to exclude
				*(uint16_t *)buf = htobe16 (0);
				buf += 2;
			}	
		}	
		if (encryption)
		{
			// session key and tag for reply
			auto& rnd = i2p::context.GetRandomNumberGenerator ();
			rnd.GenerateBlock (buf, 32); // key
			buf[32] = 1; // 1 tag
			rnd.GenerateBlock (buf + 33, 32); // tag
			if (pool)
				pool->GetLocalDestination ().SubmitSessionKey (buf, buf + 33); // introduce new key-tag to garlic engine
			else
				LogPrint ("Destination for encrypteed reply not specified");
			buf += 65;
		}	
		m->len += (buf - m->GetPayload ()); 
		FillI2NPMessageHeader (m, eI2NPDatabaseLookup);
		return m; 
	}	
Example #4
0
	void TunnelGatewayBuffer::PutI2NPMsg (const TunnelMessageBlock& block)
	{
		if (!m_CurrentTunnelDataMsg)
			CreateCurrentTunnelDataMessage ();

		// create delivery instructions
		uint8_t di[43]; // max delivery instruction length is 43 for tunnel
		size_t diLen = 1;// flag
		if (block.deliveryType != eDeliveryTypeLocal) // tunnel or router
		{	
			if (block.deliveryType == eDeliveryTypeTunnel)
			{
				*(uint32_t *)(di + diLen) = htobe32 (block.tunnelID);
				diLen += 4; // tunnelID
			}
			
			memcpy (di + diLen, block.hash, 32);
			diLen += 32; //len
		}	
		di[0] = block.deliveryType << 5; // set delivery type

		// create fragments
		I2NPMessage * msg = block.data;
		if (diLen + msg->GetLength () + 2<= m_RemainingSize)
		{
			// message fits. First and last fragment
			*(uint16_t *)(di + diLen) = htobe16 (msg->GetLength ());
			diLen += 2; // size
			memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len, di, diLen);
			memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len + diLen, msg->GetBuffer (), msg->GetLength ());
			m_CurrentTunnelDataMsg->len += diLen + msg->GetLength ();
			m_RemainingSize -= diLen + msg->GetLength ();
			if (!m_RemainingSize)
				CompleteCurrentTunnelDataMessage ();
			DeleteI2NPMessage (msg);
		}	
		else
		{
			if (diLen + 6 <= m_RemainingSize)
			{
				// delivery instructions fit
				uint32_t msgID = msg->GetHeader ()->msgID;
				size_t size = m_RemainingSize - diLen - 6; // 6 = 4 (msgID) + 2 (size)

				// first fragment
				di[0] |= 0x08; // fragmented
				*(uint32_t *)(di + diLen) = htobe32 (msgID);
				diLen += 4; // Message ID
				*(uint16_t *)(di + diLen) = htobe16 (size);
				diLen += 2; // size
				memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len, di, diLen);
				memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len + diLen, msg->GetBuffer (), size);
				m_CurrentTunnelDataMsg->len += diLen + size;
				CompleteCurrentTunnelDataMessage ();
				// follow on fragments
				int fragmentNumber = 1;
				while (size < msg->GetLength ())
				{	
					CreateCurrentTunnelDataMessage ();
					uint8_t * buf = m_CurrentTunnelDataMsg->GetBuffer ();
					buf[0] = 0x80 | (fragmentNumber << 1); // frag
					bool isLastFragment = false;
					size_t s = msg->GetLength () - size;
					if (s > TUNNEL_DATA_MAX_PAYLOAD_SIZE - 7) // 7 follow on instructions
						s = TUNNEL_DATA_MAX_PAYLOAD_SIZE - 7;	
					else // last fragment
					{	
						buf[0] |= 0x01;
						isLastFragment = true;
					}	
					*(uint32_t *)(buf + 1) = htobe32 (msgID); //Message ID
					*(uint16_t *)(buf + 5) = htobe16 (s); // size
					memcpy (buf + 7, msg->GetBuffer () + size, s);
					m_CurrentTunnelDataMsg->len += s+7;
					if (isLastFragment)
					{
						m_RemainingSize -= s+7; 
						if (!m_RemainingSize)
							CompleteCurrentTunnelDataMessage ();
					}
					else
						CompleteCurrentTunnelDataMessage ();
					size += s;
					fragmentNumber++;
				}
				DeleteI2NPMessage (msg);
			}	
			else
			{
				// delivery instructions don't fit. Create new message
				CompleteCurrentTunnelDataMessage ();
				PutI2NPMsg (block);
				// don't delete msg because it's taken care inside
			}	
		}			
	}
Example #5
0
static int
alloc_nm_txq_hwq(struct port_info *pi, struct sge_nm_txq *nm_txq)
{
	int rc, cntxt_id;
	size_t len;
	struct adapter *sc = pi->adapter;
	struct netmap_adapter *na = NA(pi->nm_ifp);
	struct fw_eq_eth_cmd c;

	MPASS(na != NULL);
	MPASS(nm_txq->desc != NULL);

	len = na->num_tx_desc * EQ_ESIZE + spg_len;
	bzero(nm_txq->desc, len);

	bzero(&c, sizeof(c));
	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_ETH_CMD) | F_FW_CMD_REQUEST |
	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_ETH_CMD_PFN(sc->pf) |
	    V_FW_EQ_ETH_CMD_VFN(0));
	c.alloc_to_len16 = htobe32(F_FW_EQ_ETH_CMD_ALLOC |
	    F_FW_EQ_ETH_CMD_EQSTART | FW_LEN16(c));
	c.autoequiqe_to_viid = htobe32(V_FW_EQ_ETH_CMD_VIID(pi->nm_viid));
	c.fetchszm_to_iqid =
	    htobe32(V_FW_EQ_ETH_CMD_HOSTFCMODE(X_HOSTFCMODE_NONE) |
		V_FW_EQ_ETH_CMD_PCIECHN(pi->tx_chan) | F_FW_EQ_ETH_CMD_FETCHRO |
		V_FW_EQ_ETH_CMD_IQID(sc->sge.nm_rxq[nm_txq->iqidx].iq_cntxt_id));
	c.dcaen_to_eqsize = htobe32(V_FW_EQ_ETH_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
		      V_FW_EQ_ETH_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
		      V_FW_EQ_ETH_CMD_EQSIZE(len / EQ_ESIZE));
	c.eqaddr = htobe64(nm_txq->ba);

	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
	if (rc != 0) {
		device_printf(pi->dev,
		    "failed to create netmap egress queue: %d\n", rc);
		return (rc);
	}

	nm_txq->cntxt_id = G_FW_EQ_ETH_CMD_EQID(be32toh(c.eqid_pkd));
	cntxt_id = nm_txq->cntxt_id - sc->sge.eq_start;
	if (cntxt_id >= sc->sge.neq)
	    panic("%s: nm_txq->cntxt_id (%d) more than the max (%d)", __func__,
		cntxt_id, sc->sge.neq - 1);
	sc->sge.eqmap[cntxt_id] = (void *)nm_txq;

	nm_txq->pidx = nm_txq->cidx = 0;
	MPASS(nm_txq->sidx == na->num_tx_desc);
	nm_txq->equiqidx = nm_txq-> equeqidx = nm_txq->dbidx = 0;

	nm_txq->doorbells = sc->doorbells;
	if (isset(&nm_txq->doorbells, DOORBELL_UDB) ||
	    isset(&nm_txq->doorbells, DOORBELL_UDBWC) ||
	    isset(&nm_txq->doorbells, DOORBELL_WCWR)) {
		uint32_t s_qpp = sc->sge.eq_s_qpp;
		uint32_t mask = (1 << s_qpp) - 1;
		volatile uint8_t *udb;

		udb = sc->udbs_base + UDBS_DB_OFFSET;
		udb += (nm_txq->cntxt_id >> s_qpp) << PAGE_SHIFT;
		nm_txq->udb_qid = nm_txq->cntxt_id & mask;
		if (nm_txq->udb_qid >= PAGE_SIZE / UDBS_SEG_SIZE)
	    		clrbit(&nm_txq->doorbells, DOORBELL_WCWR);
		else {
			udb += nm_txq->udb_qid << UDBS_SEG_SHIFT;
			nm_txq->udb_qid = 0;
		}
		nm_txq->udb = (volatile void *)udb;
	}
Example #6
0
void
send_flowc_wr(struct toepcb *toep, struct flowc_tx_params *ftxp)
{
	struct wrqe *wr;
	struct fw_flowc_wr *flowc;
	unsigned int nparams = ftxp ? 8 : 6, flowclen;
	struct port_info *pi = toep->port;
	struct adapter *sc = pi->adapter;
	unsigned int pfvf = G_FW_VIID_PFN(pi->viid) << S_FW_VIID_PFN;
	struct ofld_tx_sdesc *txsd = &toep->txsd[toep->txsd_pidx];

	KASSERT(!(toep->flags & TPF_FLOWC_WR_SENT),
	    ("%s: flowc for tid %u sent already", __func__, toep->tid));

	CTR2(KTR_CXGBE, "%s: tid %u", __func__, toep->tid);

	flowclen = sizeof(*flowc) + nparams * sizeof(struct fw_flowc_mnemval);

	wr = alloc_wrqe(roundup(flowclen, 16), toep->ofld_txq);
	if (wr == NULL) {
		/* XXX */
		panic("%s: allocation failure.", __func__);
	}
	flowc = wrtod(wr);
	memset(flowc, 0, wr->wr_len);

	flowc->op_to_nparams = htobe32(V_FW_WR_OP(FW_FLOWC_WR) |
	    V_FW_FLOWC_WR_NPARAMS(nparams));
	flowc->flowid_len16 = htonl(V_FW_WR_LEN16(howmany(flowclen, 16)) |
	    V_FW_WR_FLOWID(toep->tid));

	flowc->mnemval[0].mnemonic = FW_FLOWC_MNEM_PFNVFN;
	flowc->mnemval[0].val = htobe32(pfvf);
	flowc->mnemval[1].mnemonic = FW_FLOWC_MNEM_CH;
	flowc->mnemval[1].val = htobe32(pi->tx_chan);
	flowc->mnemval[2].mnemonic = FW_FLOWC_MNEM_PORT;
	flowc->mnemval[2].val = htobe32(pi->tx_chan);
	flowc->mnemval[3].mnemonic = FW_FLOWC_MNEM_IQID;
	flowc->mnemval[3].val = htobe32(toep->ofld_rxq->iq.abs_id);
	if (ftxp) {
		uint32_t sndbuf = min(ftxp->snd_space, sc->tt.sndbuf);

		flowc->mnemval[4].mnemonic = FW_FLOWC_MNEM_SNDNXT;
		flowc->mnemval[4].val = htobe32(ftxp->snd_nxt);
		flowc->mnemval[5].mnemonic = FW_FLOWC_MNEM_RCVNXT;
		flowc->mnemval[5].val = htobe32(ftxp->rcv_nxt);
		flowc->mnemval[6].mnemonic = FW_FLOWC_MNEM_SNDBUF;
		flowc->mnemval[6].val = htobe32(sndbuf);
		flowc->mnemval[7].mnemonic = FW_FLOWC_MNEM_MSS;
		flowc->mnemval[7].val = htobe32(ftxp->mss);
	} else {
		flowc->mnemval[4].mnemonic = FW_FLOWC_MNEM_SNDBUF;
		flowc->mnemval[4].val = htobe32(512);
		flowc->mnemval[5].mnemonic = FW_FLOWC_MNEM_MSS;
		flowc->mnemval[5].val = htobe32(512);
	}

	txsd->tx_credits = howmany(flowclen, 16);
	txsd->plen = 0;
	KASSERT(toep->tx_credits >= txsd->tx_credits && toep->txsd_avail > 0,
	    ("%s: not enough credits (%d)", __func__, toep->tx_credits));
	toep->tx_credits -= txsd->tx_credits;
	if (__predict_false(++toep->txsd_pidx == toep->txsd_total))
		toep->txsd_pidx = 0;
	toep->txsd_avail--;

	toep->flags |= TPF_FLOWC_WR_SENT;
        t4_wrq_tx(sc, wr);
}
Example #7
0
 static T host_to_network(T value) { return htobe32(value); }
Example #8
0
enum nss_status _nss_myhostname_gethostbyaddr2_r(
                const void* addr, socklen_t len,
                int af,
                struct hostent *host,
                char *buffer, size_t buflen,
                int *errnop, int *h_errnop,
                int32_t *ttlp) {

        const char *canonical = NULL, *additional = NULL;
        uint32_t local_address_ipv4 = LOCALADDRESS_IPV4;
        _cleanup_free_ struct local_address *addresses = NULL;
        _cleanup_free_ char *hn = NULL;
        int n_addresses = 0;
        struct local_address *a;
        bool additional_from_hostname = false;
        unsigned n;

        PROTECT_ERRNO;
        BLOCK_SIGNALS(NSS_SIGNALS_BLOCK);

        assert(addr);
        assert(host);
        assert(buffer);
        assert(errnop);
        assert(h_errnop);

        if (!IN_SET(af, AF_INET, AF_INET6)) {
                *errnop = EAFNOSUPPORT;
                *h_errnop = NO_DATA;
                return NSS_STATUS_UNAVAIL;
        }

        if (len != FAMILY_ADDRESS_SIZE(af)) {
                *errnop = EINVAL;
                *h_errnop = NO_RECOVERY;
                return NSS_STATUS_UNAVAIL;
        }

        if (af == AF_INET) {
                if ((*(uint32_t*) addr) == LOCALADDRESS_IPV4)
                        goto found;

                if ((*(uint32_t*) addr) == htobe32(INADDR_LOOPBACK)) {
                        canonical = "localhost";
                        local_address_ipv4 = htobe32(INADDR_LOOPBACK);
                        goto found;
                }

        } else {
                assert(af == AF_INET6);

                if (memcmp(addr, LOCALADDRESS_IPV6, 16) == 0) {
                        canonical = "localhost";
                        additional_from_hostname = true;
                        goto found;
                }
        }

        n_addresses = local_addresses(NULL, 0, AF_UNSPEC, &addresses);
        for (a = addresses, n = 0; (int) n < n_addresses; n++, a++) {
                if (af != a->family)
                        continue;

                if (memcmp(addr, &a->address, FAMILY_ADDRESS_SIZE(af)) == 0)
                        goto found;
        }

        addresses = mfree(addresses);

        n_addresses = local_gateways(NULL, 0, AF_UNSPEC, &addresses);
        for (a = addresses, n = 0; (int) n < n_addresses; n++, a++) {
                if (af != a->family)
                        continue;

                if (memcmp(addr, &a->address, FAMILY_ADDRESS_SIZE(af)) == 0) {
                        canonical = "_gateway";
                        goto found;
                }
        }

        *h_errnop = HOST_NOT_FOUND;
        return NSS_STATUS_NOTFOUND;

found:
        if (!canonical || additional_from_hostname) {
                hn = gethostname_malloc();
                if (!hn) {
                        *errnop = ENOMEM;
                        *h_errnop = NO_RECOVERY;
                        return NSS_STATUS_TRYAGAIN;
                }

                if (!canonical)
                        canonical = hn;
                else
                        additional = hn;
        }

        return fill_in_hostent(
                        canonical, additional,
                        af,
                        addresses, n_addresses,
                        local_address_ipv4,
                        host,
                        buffer, buflen,
                        errnop, h_errnop,
                        ttlp,
                        NULL);
}
Example #9
0
int
main(int argc, char *argv[])
{
	const char *fwname, *udevname;
	char msgdev[256], datadev[256];
	struct uath_fwmsg txmsg, rxmsg;
	char *txdata;
	struct stat sb;
	int msg, data, fw, timeout, b, c;
	int bufsize = 512, verbose = 0;
	ssize_t len;

	udevname = NULL;
	while ((c = getopt(argc, argv, "d:v")) != -1) {
		switch (c) {
		case 'd':
			udevname = optarg;
			break;
		case 'v':
			verbose = 1;
			break;
		default:
			usage();
			/*NOTREACHED*/
		}
	}
	argc -= optind;
	argv += optind;

	if (udevname == NULL)
		errx(-1, "No device name; use -d to specify the ugen device");
	if (argc > 1)
		usage();

	if (argc == 1)
		fwname = argv[0];
	else
		fwname = _PATH_FIRMWARE "/ar5523.bin";
	fw = open(fwname, O_RDONLY, 0);
	if (fw < 0)
		err(-1, "open(%s)", fwname);
	if (fstat(fw, &sb) < 0)
		err(-1, "fstat(%s)", fwname);
	txdata = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fw, 0);
	if (txdata == MAP_FAILED)
		err(-1, "mmap(%s)", fwname);
	len = sb.st_size;
	/* XXX verify device is an AR5005 part */
	if (getdevname(udevname, msgdev, datadev))
		err(-1, "getdevname error");

	msg = open(msgdev, O_RDWR, 0);
	if (msg < 0)
		err(-1, "open(%s)", msgdev);
	timeout = UATH_DATA_TIMEOUT;
	if (ioctl(msg, USB_SET_RX_TIMEOUT, &timeout) < 0)
		err(-1, "%s: USB_SET_RX_TIMEOUT(%u)", msgdev, UATH_DATA_TIMEOUT);
	if (ioctl(msg, USB_SET_RX_BUFFER_SIZE, &bufsize) < 0)
		err(-1, "%s: USB_SET_RX_BUFFER_SIZE(%u)", msgdev, bufsize);

	data = open(datadev, O_WRONLY, 0);
	if (data < 0)
		err(-1, "open(%s)", datadev);
	timeout = UATH_DATA_TIMEOUT;
	if (ioctl(data, USB_SET_TX_TIMEOUT, &timeout) < 0)
		err(-1, "%s: USB_SET_TX_TIMEOUT(%u)", datadev,
		    UATH_DATA_TIMEOUT);

	VERBOSE("Load firmware %s to %s\n", fwname, udevname);

	bzero(&txmsg, sizeof (struct uath_fwmsg));
	txmsg.flags = htobe32(UATH_WRITE_BLOCK);
	txmsg.total = htobe32(len);

	b = 0;
	while (len > 0) {
		int mlen;

		mlen = len;
		if (mlen > UATH_MAX_FWBLOCK_SIZE)
			mlen = UATH_MAX_FWBLOCK_SIZE;
		txmsg.remain = htobe32(len - mlen);
		txmsg.len = htobe32(mlen);

		/* send firmware block meta-data */
		VERBOSE("send block %2u: %zd bytes remaining", b, len - mlen);
		if (write(msg, &txmsg, sizeof(txmsg)) != sizeof(txmsg)) {
			VERBOSE("%s", "\n");
			err(-1, "error sending msg (%s)", msgdev);
			break;
		}

		/* send firmware block data */
		VERBOSE("%s", "\n             : data...");
		if (write(data, txdata, mlen) != mlen) {
			VERBOSE("%s", "\n");
			err(-1, "error sending data (%s)", datadev);
			break;
		}

		/* wait for ack from firmware */
		VERBOSE("%s", "\n             : wait for ack...");
		bzero(&rxmsg, sizeof(rxmsg));
		if (read(msg, &rxmsg, sizeof(rxmsg)) != sizeof(rxmsg)) {
			VERBOSE("%s", "\n");
			err(-1, "error reading msg (%s)", msgdev);
			break;
		}

		VERBOSE("flags=0x%x total=%d\n",
		    be32toh(rxmsg.flags), be32toh(rxmsg.rxtotal));
		len -= mlen;
		txdata += mlen;
		b++;
	}
	sleep(1);
	close(fw);
	close(msg);
	close(data);
	return 0;
}
Example #10
0
enum nss_status _nss_myhostname_gethostbyname4_r(
                const char *name,
                struct gaih_addrtuple **pat,
                char *buffer, size_t buflen,
                int *errnop, int *h_errnop,
                int32_t *ttlp) {

        struct gaih_addrtuple *r_tuple, *r_tuple_prev = NULL;
        _cleanup_free_ struct local_address *addresses = NULL;
        _cleanup_free_ char *hn = NULL;
        const char *canonical = NULL;
        int n_addresses = 0;
        uint32_t local_address_ipv4;
        struct local_address *a;
        size_t l, idx, ms;
        char *r_name;
        unsigned n;

        PROTECT_ERRNO;
        BLOCK_SIGNALS(NSS_SIGNALS_BLOCK);

        assert(name);
        assert(pat);
        assert(buffer);
        assert(errnop);
        assert(h_errnop);

        if (is_localhost(name)) {
                /* We respond to 'localhost', so that /etc/hosts
                 * is optional */

                canonical = "localhost";
                local_address_ipv4 = htobe32(INADDR_LOOPBACK);

        } else if (is_gateway_hostname(name)) {

                n_addresses = local_gateways(NULL, 0, AF_UNSPEC, &addresses);
                if (n_addresses <= 0) {
                        *h_errnop = HOST_NOT_FOUND;
                        return NSS_STATUS_NOTFOUND;
                }

                canonical = "_gateway";

        } else {
                hn = gethostname_malloc();
                if (!hn) {
                        *errnop = ENOMEM;
                        *h_errnop = NO_RECOVERY;
                        return NSS_STATUS_TRYAGAIN;
                }

                /* We respond to our local host name, our hostname suffixed with a single dot. */
                if (!streq(name, hn) && !streq_ptr(startswith(name, hn), ".")) {
                        *h_errnop = HOST_NOT_FOUND;
                        return NSS_STATUS_NOTFOUND;
                }

                n_addresses = local_addresses(NULL, 0, AF_UNSPEC, &addresses);
                if (n_addresses < 0)
                        n_addresses = 0;

                canonical = hn;
                local_address_ipv4 = LOCALADDRESS_IPV4;
        }

        l = strlen(canonical);
        ms = ALIGN(l+1) + ALIGN(sizeof(struct gaih_addrtuple)) * (n_addresses > 0 ? n_addresses : 2);
        if (buflen < ms) {
                *errnop = ERANGE;
                *h_errnop = NETDB_INTERNAL;
                return NSS_STATUS_TRYAGAIN;
        }

        /* First, fill in hostname */
        r_name = buffer;
        memcpy(r_name, canonical, l+1);
        idx = ALIGN(l+1);

        assert(n_addresses >= 0);
        if (n_addresses == 0) {
                /* Second, fill in IPv6 tuple */
                r_tuple = (struct gaih_addrtuple*) (buffer + idx);
                r_tuple->next = r_tuple_prev;
                r_tuple->name = r_name;
                r_tuple->family = AF_INET6;
                memcpy(r_tuple->addr, LOCALADDRESS_IPV6, 16);
                r_tuple->scopeid = 0;

                idx += ALIGN(sizeof(struct gaih_addrtuple));
                r_tuple_prev = r_tuple;

                /* Third, fill in IPv4 tuple */
                r_tuple = (struct gaih_addrtuple*) (buffer + idx);
                r_tuple->next = r_tuple_prev;
                r_tuple->name = r_name;
                r_tuple->family = AF_INET;
                *(uint32_t*) r_tuple->addr = local_address_ipv4;
                r_tuple->scopeid = 0;

                idx += ALIGN(sizeof(struct gaih_addrtuple));
                r_tuple_prev = r_tuple;
        }

        /* Fourth, fill actual addresses in, but in backwards order */
        for (a = addresses + n_addresses - 1, n = 0; (int) n < n_addresses; n++, a--) {
                r_tuple = (struct gaih_addrtuple*) (buffer + idx);
                r_tuple->next = r_tuple_prev;
                r_tuple->name = r_name;
                r_tuple->family = a->family;
                r_tuple->scopeid = a->family == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(&a->address.in6) ? a->ifindex : 0;
                memcpy(r_tuple->addr, &a->address, 16);

                idx += ALIGN(sizeof(struct gaih_addrtuple));
                r_tuple_prev = r_tuple;
        }

        /* Verify the size matches */
        assert(idx == ms);

        /* Nscd expects us to store the first record in **pat. */
        if (*pat)
                **pat = *r_tuple_prev;
        else
                *pat = r_tuple_prev;

        if (ttlp)
                *ttlp = 0;

        /* Explicitly reset both *h_errnop and h_errno to work around
         * https://bugzilla.redhat.com/show_bug.cgi?id=1125975 */
        *h_errnop = NETDB_SUCCESS;
        h_errno = 0;

        return NSS_STATUS_SUCCESS;
}
Example #11
0
enum nss_status _nss_myhostname_gethostbyname3_r(
                const char *name,
                int af,
                struct hostent *host,
                char *buffer, size_t buflen,
                int *errnop, int *h_errnop,
                int32_t *ttlp,
                char **canonp) {

        _cleanup_free_ struct local_address *addresses = NULL;
        const char *canonical, *additional = NULL;
        _cleanup_free_ char *hn = NULL;
        uint32_t local_address_ipv4 = 0;
        int n_addresses = 0;

        PROTECT_ERRNO;
        BLOCK_SIGNALS(NSS_SIGNALS_BLOCK);

        assert(name);
        assert(host);
        assert(buffer);
        assert(errnop);
        assert(h_errnop);

        if (af == AF_UNSPEC)
                af = AF_INET;

        if (!IN_SET(af, AF_INET, AF_INET6)) {
                *errnop = EAFNOSUPPORT;
                *h_errnop = NO_DATA;
                return NSS_STATUS_UNAVAIL;
        }

        if (is_localhost(name)) {
                canonical = "localhost";
                local_address_ipv4 = htobe32(INADDR_LOOPBACK);

        } else if (is_gateway_hostname(name)) {

                n_addresses = local_gateways(NULL, 0, af, &addresses);
                if (n_addresses <= 0) {
                        *h_errnop = HOST_NOT_FOUND;
                        return NSS_STATUS_NOTFOUND;
                }

                canonical = "_gateway";

        } else {
                hn = gethostname_malloc();
                if (!hn) {
                        *errnop = ENOMEM;
                        *h_errnop = NO_RECOVERY;
                        return NSS_STATUS_TRYAGAIN;
                }

                if (!streq(name, hn) && !streq_ptr(startswith(name, hn), ".")) {
                        *h_errnop = HOST_NOT_FOUND;
                        return NSS_STATUS_NOTFOUND;
                }

                n_addresses = local_addresses(NULL, 0, af, &addresses);
                if (n_addresses < 0)
                        n_addresses = 0;

                canonical = hn;
                additional = n_addresses <= 0 && af == AF_INET6 ? "localhost" : NULL;
                local_address_ipv4 = LOCALADDRESS_IPV4;
        }

        return fill_in_hostent(
                        canonical, additional,
                        af,
                        addresses, n_addresses,
                        local_address_ipv4,
                        host,
                        buffer, buflen,
                        errnop, h_errnop,
                        ttlp,
                        canonp);
}
Example #12
0
int
mb_put_uint32be(struct mbchain *mbp, uint32_t x)
{
	x = htobe32(x);
	return (mb_put_mem(mbp, (caddr_t)&x, sizeof(x), MB_MSYSTEM));
}
Example #13
0
/*
 * Sniff Bluetooth Low Energy packets.
 */
void cb_btle(void* args, usb_pkt_rx *rx, int bank)
{
	lell_packet * pkt;
	btle_options * opts = (btle_options *) args;
	int i;
	u32 access_address = 0;

	static u32 prev_ts = 0;
	uint32_t refAA;
	int8_t sig, noise;

	UNUSED(bank);

	uint64_t nowns = now_ns_from_clk100ns( rx );

	/* Sanity check */
	if (rx->channel > (NUM_BREDR_CHANNELS-1))
		return;

	if (infile == NULL)
		systime = time(NULL);

	/* Dump to sumpfile if specified */
	if (dumpfile) {
		uint32_t systime_be = htobe32(systime);
		if (fwrite(&systime_be, sizeof(systime_be), 1, dumpfile) != 1) {;}
		if (fwrite(rx, sizeof(usb_pkt_rx), 1, dumpfile) != 1) {;}
	}

	lell_allocate_and_decode(rx->data, rx->channel + 2402, rx->clk100ns, &pkt);

	/* do nothing further if filtered due to bad AA */
	if (opts &&
	    (opts->allowed_access_address_errors <
	     lell_get_access_address_offenses(pkt))) {
		lell_packet_unref(pkt);
		return;
	}

	/* Dump to PCAP/PCAPNG if specified */
	refAA = lell_packet_is_data(pkt) ? 0 : 0x8e89bed6;
	determine_signal_and_noise( rx, &sig, &noise );	
#if defined(USE_PCAP)
	if (h_pcap_le) {
		/* only one of these two will succeed, depending on
		 * whether PCAP was opened with DLT_PPI or not */
		lell_pcap_append_packet(h_pcap_le, nowns,
					sig, noise,
					refAA, pkt);
		lell_pcap_append_ppi_packet(h_pcap_le, nowns,
					    rx->clkn_high, 
					    rx->rssi_min, rx->rssi_max,
					    rx->rssi_avg, rx->rssi_count,
					    pkt);
	}
#endif
	if (h_pcapng_le) {
		lell_pcapng_append_packet(h_pcapng_le, nowns,
					  sig, noise,
					  refAA, pkt);
	}

	u32 ts_diff = rx->clk100ns - prev_ts;
	prev_ts = rx->clk100ns;
	printf("systime=%u freq=%d addr=%08x delta_t=%.03f ms\n",
	       systime, rx->channel + 2402, lell_get_access_address(pkt),
	       ts_diff / 10000.0);

	int len = (rx->data[5] & 0x3f) + 6 + 3;
	if (len > 50) len = 50;

	for (i = 4; i < len; ++i)
		printf("%02x ", rx->data[i]);
	printf("\n");

	lell_print(pkt);
	printf("\n");

	lell_packet_unref(pkt);

	fflush(stdout);
}
Example #14
0
/* Sniff for LAPs. If a piconet is provided, use the given LAP to
 * search for UAP.
 */
static void cb_br_rx(void* args, usb_pkt_rx *rx, int bank)
{
	btbb_packet *pkt = NULL;
	btbb_piconet *pn = (btbb_piconet *)args;
	char syms[BANK_LEN * NUM_BANKS];
	int i;
	int8_t signal_level;
	int8_t noise_level;
	int8_t snr;
	int offset;
	uint32_t clkn;
	uint32_t lap = LAP_ANY;
	uint8_t uap = UAP_ANY;

	/* Sanity check */
	if (rx->channel > (NUM_BREDR_CHANNELS-1))
		goto out;

	/* Copy packet (for dump) */
	memcpy(&usb_packets[bank], rx, sizeof(usb_pkt_rx));

	unpack_symbols(rx->data, br_symbols[bank]);

	/* Do analysis based on oldest packet */
	rx = &usb_packets[ (bank+1) % NUM_BANKS ];
	uint64_t nowns = now_ns_from_clk100ns( rx );

	determine_signal_and_noise( rx, &signal_level, &noise_level );
	snr = signal_level - noise_level;

	/* WC4: use vm circbuf if target allows. This gets rid of this
	 * wrapped copy step. */

	/* Copy 2 oldest banks of symbols for analysis. Packet may
	 * cross a bank boundary. */
	for (i = 0; i < 2; i++)
		memcpy(syms + i * BANK_LEN,
		       br_symbols[(i + 1 + bank) % NUM_BANKS],
		       BANK_LEN);
	
	/* Look for packets with specified LAP, if given. Otherwise
	 * search for any packet.  Also determine if UAP is known. */
	if (pn) {
		lap = btbb_piconet_get_flag(pn, BTBB_LAP_VALID) ? btbb_piconet_get_lap(pn) : LAP_ANY;
		uap = btbb_piconet_get_flag(pn, BTBB_UAP_VALID) ? btbb_piconet_get_uap(pn) : UAP_ANY;
	}

	/* Pass packet-pointer-pointer so that
	 * packet can be created in libbtbb. */
	offset = btbb_find_ac(syms, BANK_LEN, lap, max_ac_errors, &pkt);
	if (offset < 0)
		goto out;

	/* Copy out remaining banks of symbols for full analysis. */
	for (i = 1; i < NUM_BANKS; i++)
		memcpy(syms + i * BANK_LEN,
		       br_symbols[(i + 1 + bank) % NUM_BANKS],
		       BANK_LEN);

	/* Once offset is known for a valid packet, copy in symbols
	 * and other rx data. CLKN here is the 312.5us CLK27-0. The
	 * btbb library can shift it be CLK1 if needed. */
	clkn = (rx->clkn_high << 20) + (le32toh(rx->clk100ns) + offset + 1562) / 3125;
	btbb_packet_set_data(pkt, syms + offset, NUM_BANKS * BANK_LEN - offset,
			   rx->channel, clkn);

	/* Dump to PCAP/PCAPNG if specified */
#if defined(USE_PCAP)
        if (h_pcap_bredr) {
		btbb_pcap_append_packet(h_pcap_bredr, nowns,
					signal_level, noise_level,
					lap, uap, pkt);
        }
#endif
	if (h_pcapng_bredr) {
		btbb_pcapng_append_packet(h_pcapng_bredr, nowns, 
					  signal_level, noise_level,
					  lap, uap, pkt);
	}

	/* When reading from file, caller will read
	 * systime before calling this routine, so do
	 * not overwrite. Otherwise, get current time. */
	if (infile == NULL)
		systime = time(NULL);

	/* If dumpfile is specified, write out all banks to the
	 * file. There could be duplicate data in the dump if more
	 * than one LAP is found within the span of NUM_BANKS. */
	if (dumpfile) {
		for(i = 0; i < NUM_BANKS; i++) {
			uint32_t systime_be = htobe32(systime);
			if (fwrite(&systime_be, 
				   sizeof(systime_be), 1,
				   dumpfile)
			    != 1) {;}
			if (fwrite(&usb_packets[(i + 1 + bank) % NUM_BANKS],
				   sizeof(usb_pkt_rx), 1, dumpfile)
			    != 1) {;}
		}
	}

	printf("systime=%u ch=%2d LAP=%06x err=%u clk100ns=%u clk1=%u s=%d n=%d snr=%d\n",
	       (int)systime,
	       btbb_packet_get_channel(pkt),
	       btbb_packet_get_lap(pkt),
	       btbb_packet_get_ac_errors(pkt),
	       rx->clk100ns,
	       btbb_packet_get_clkn(pkt),
	       signal_level,
	       noise_level,
	       snr);

	i = btbb_process_packet(pkt, pn);
	if(i < 0) {
		follow_pn = pn;
		stop_ubertooth = 1;
	}

out:
	if (pkt)
		btbb_packet_unref(pkt);
}
Example #15
0
static int test_client_verify_request(DHCP6Message *request, uint8_t *option,
                                      size_t len) {
        _cleanup_(sd_dhcp6_lease_unrefp) sd_dhcp6_lease *lease = NULL;
        uint8_t *optval;
        uint16_t optcode;
        size_t optlen;
        bool found_clientid = false, found_iana = false, found_serverid = false,
                found_elapsed_time = false;
        int r;
        struct in6_addr addr;
        be32_t val;
        uint32_t lt_pref, lt_valid;

        assert_se(request->type == DHCP6_REQUEST);

        assert_se(dhcp6_lease_new(&lease) >= 0);

        while ((r = dhcp6_option_parse(&option, &len,
                                       &optcode, &optlen, &optval)) >= 0) {
                switch(optcode) {
                case SD_DHCP6_OPTION_CLIENTID:
                        assert_se(!found_clientid);
                        found_clientid = true;

                        assert_se(!memcmp(optval, &test_duid,
                                          sizeof(test_duid)));

                        break;

                case SD_DHCP6_OPTION_IA_NA:
                        assert_se(!found_iana);
                        found_iana = true;


                        assert_se(optlen == 40);
                        assert_se(!memcmp(optval, &test_iaid, sizeof(test_iaid)));

                        val = htobe32(80);
                        assert_se(!memcmp(optval + 4, &val, sizeof(val)));

                        val = htobe32(120);
                        assert_se(!memcmp(optval + 8, &val, sizeof(val)));

                        assert_se(!dhcp6_option_parse_ia(&optval, &optlen,
                                                         optcode, &lease->ia));

                        break;

                case SD_DHCP6_OPTION_SERVERID:
                        assert_se(!found_serverid);
                        found_serverid = true;

                        assert_se(optlen == 14);
                        assert_se(!memcmp(&msg_advertise[179], optval, optlen));

                        break;

                case SD_DHCP6_OPTION_ELAPSED_TIME:
                        assert_se(!found_elapsed_time);
                        found_elapsed_time = true;

                        assert_se(optlen == 2);

                        break;
                }
        }

        assert_se(r == -ENOMSG);
        assert_se(found_clientid && found_iana && found_serverid &&
                  found_elapsed_time);

        sd_dhcp6_lease_reset_address_iter(lease);
        assert_se(sd_dhcp6_lease_get_address(lease, &addr, &lt_pref,
                                             &lt_valid) >= 0);
        assert_se(!memcmp(&addr, &msg_advertise[42], sizeof(addr)));
        assert_se(lt_pref == 150);
        assert_se(lt_valid == 180);

        assert_se(sd_dhcp6_lease_get_address(lease, &addr, &lt_pref,
                                             &lt_valid) == -ENOMSG);

        return 0;
}
Example #16
0
template <> inline uint32_t host_to  <uint32_t, big_endian>(uint32_t value) { return htobe32(value); }
Example #17
0
/*
 * SHA256 block compression function.  The 256-bit state is transformed via
 * the 512-bit input block to produce a new state.
 */
static void
SHA256_Transform(uint32_t * state, const uint32_t block[16], int swap)
{
	uint32_t W[64];
	uint32_t S[8];
	uint32_t t0, t1;
	int i;

	/* 1. Prepare message schedule W. */
	if(swap)
		for (i = 0; i < 16; i++)
			W[i] = htobe32(block[i]);
	else
		memcpy(W, block, 64);
	for (i = 16; i < 64; i += 2) {
		W[i] = s1(W[i - 2]) + W[i - 7] + s0(W[i - 15]) + W[i - 16];
		W[i+1] = s1(W[i - 1]) + W[i - 6] + s0(W[i - 14]) + W[i - 15];
	}

	/* 2. Initialize working variables. */
	memcpy(S, state, 32);

	/* 3. Mix. */
	RNDr(S, W, 0, 0x428a2f98);
	RNDr(S, W, 1, 0x71374491);
	RNDr(S, W, 2, 0xb5c0fbcf);
	RNDr(S, W, 3, 0xe9b5dba5);
	RNDr(S, W, 4, 0x3956c25b);
	RNDr(S, W, 5, 0x59f111f1);
	RNDr(S, W, 6, 0x923f82a4);
	RNDr(S, W, 7, 0xab1c5ed5);
	RNDr(S, W, 8, 0xd807aa98);
	RNDr(S, W, 9, 0x12835b01);
	RNDr(S, W, 10, 0x243185be);
	RNDr(S, W, 11, 0x550c7dc3);
	RNDr(S, W, 12, 0x72be5d74);
	RNDr(S, W, 13, 0x80deb1fe);
	RNDr(S, W, 14, 0x9bdc06a7);
	RNDr(S, W, 15, 0xc19bf174);
	RNDr(S, W, 16, 0xe49b69c1);
	RNDr(S, W, 17, 0xefbe4786);
	RNDr(S, W, 18, 0x0fc19dc6);
	RNDr(S, W, 19, 0x240ca1cc);
	RNDr(S, W, 20, 0x2de92c6f);
	RNDr(S, W, 21, 0x4a7484aa);
	RNDr(S, W, 22, 0x5cb0a9dc);
	RNDr(S, W, 23, 0x76f988da);
	RNDr(S, W, 24, 0x983e5152);
	RNDr(S, W, 25, 0xa831c66d);
	RNDr(S, W, 26, 0xb00327c8);
	RNDr(S, W, 27, 0xbf597fc7);
	RNDr(S, W, 28, 0xc6e00bf3);
	RNDr(S, W, 29, 0xd5a79147);
	RNDr(S, W, 30, 0x06ca6351);
	RNDr(S, W, 31, 0x14292967);
	RNDr(S, W, 32, 0x27b70a85);
	RNDr(S, W, 33, 0x2e1b2138);
	RNDr(S, W, 34, 0x4d2c6dfc);
	RNDr(S, W, 35, 0x53380d13);
	RNDr(S, W, 36, 0x650a7354);
	RNDr(S, W, 37, 0x766a0abb);
	RNDr(S, W, 38, 0x81c2c92e);
	RNDr(S, W, 39, 0x92722c85);
	RNDr(S, W, 40, 0xa2bfe8a1);
	RNDr(S, W, 41, 0xa81a664b);
	RNDr(S, W, 42, 0xc24b8b70);
	RNDr(S, W, 43, 0xc76c51a3);
	RNDr(S, W, 44, 0xd192e819);
	RNDr(S, W, 45, 0xd6990624);
	RNDr(S, W, 46, 0xf40e3585);
	RNDr(S, W, 47, 0x106aa070);
	RNDr(S, W, 48, 0x19a4c116);
	RNDr(S, W, 49, 0x1e376c08);
	RNDr(S, W, 50, 0x2748774c);
	RNDr(S, W, 51, 0x34b0bcb5);
	RNDr(S, W, 52, 0x391c0cb3);
	RNDr(S, W, 53, 0x4ed8aa4a);
	RNDr(S, W, 54, 0x5b9cca4f);
	RNDr(S, W, 55, 0x682e6ff3);
	RNDr(S, W, 56, 0x748f82ee);
	RNDr(S, W, 57, 0x78a5636f);
	RNDr(S, W, 58, 0x84c87814);
	RNDr(S, W, 59, 0x8cc70208);
	RNDr(S, W, 60, 0x90befffa);
	RNDr(S, W, 61, 0xa4506ceb);
	RNDr(S, W, 62, 0xbef9a3f7);
	RNDr(S, W, 63, 0xc67178f2);

	/* 4. Mix local working variables into global state */
	for (i = 0; i < 8; i++)
		state[i] += S[i];
}
Example #18
0
template <> inline int32_t host_to  <int32_t, big_endian>(int32_t value) { return (int32_t)htobe32((uint32_t)value); }
Example #19
0
/*
 * Check version numbers on the relayd.
 * If major versions are compatible, we assign minor_to_use to the
 * minor version of the procotol we are going to use for this session.
 *
 * Return 0 if compatible else negative value.
 */
int relayd_version_check(struct lttcomm_relayd_sock *rsock)
{
	int ret;
	struct lttcomm_relayd_version msg;

	/* Code flow error. Safety net. */
	assert(rsock);

	DBG("Relayd version check for major.minor %u.%u", rsock->major,
			rsock->minor);

	memset(&msg, 0, sizeof(msg));
	/* Prepare network byte order before transmission. */
	msg.major = htobe32(rsock->major);
	msg.minor = htobe32(rsock->minor);

	/* Send command */
	ret = send_command(rsock, RELAYD_VERSION, (void *) &msg, sizeof(msg), 0);
	if (ret < 0) {
		goto error;
	}

	/* Receive response */
	ret = recv_reply(rsock, (void *) &msg, sizeof(msg));
	if (ret < 0) {
		goto error;
	}

	/* Set back to host bytes order */
	msg.major = be32toh(msg.major);
	msg.minor = be32toh(msg.minor);

	/*
	 * Only validate the major version. If the other side is higher,
	 * communication is not possible. Only major version equal can talk to each
	 * other. If the minor version differs, the lowest version is used by both
	 * sides.
	 */
	if (msg.major != rsock->major) {
		/* Not compatible */
		ret = -1;
		DBG2("Relayd version is NOT compatible. Relayd version %u != %u (us)",
				msg.major, rsock->major);
		goto error;
	}

	/*
	 * If the relayd's minor version is higher, it will adapt to our version so
	 * we can continue to use the latest relayd communication data structure.
	 * If the received minor version is higher, the relayd should adapt to us.
	 */
	if (rsock->minor > msg.minor) {
		rsock->minor = msg.minor;
	}

	/* Version number compatible */
	DBG2("Relayd version is compatible, using protocol version %u.%u",
			rsock->major, rsock->minor);
	ret = 0;

error:
	return ret;
}
static bool notification_signal_exit(struct notify_info *notify,
				     unsigned int code)
{
	struct notify_msg_exit		msg = {
		.op		= 'E',
		.code		= htobe32(code),
	};

	return notification_send(notify, &msg, sizeof msg);
}

static bool notification_send_length(struct notify_info *notify, size_t len)
{
	struct notify_msg_length	msg = {
		.op		= 'L',
		.length		= htobe64(len),
	};

	return notification_send(notify, &msg, sizeof msg);
}

static bool notification_handle_read(struct notify_info *notify, size_t cnt)
{
	struct notify_msg_read		msg = {
		.op		= 'R',
		.count		= htobe64(notify->cur_pos + cnt),
	};

	notify->cur_pos += cnt;

	return notification_send(notify, &msg, sizeof msg);
}

static bool notification_init(struct notify_info *notify, int port)
{
	int		fd;

	if (port == -1) {
		notify->fd = -1;
		return true;
	}

	fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
	if (fd < 0) {
		perror("socket(<notification>)");
		return false;
	}

	notify->fd   = fd;

	/* assume IPv4 for now; change for IPv6 when needed */
	notify->dst.ip4 = (struct sockaddr_in) {
		.sin_family	= AF_INET,
		.sin_port	= htons(port),
		.sin_addr	= { htonl(INADDR_LOOPBACK) },
	};
	notify->dst_len = sizeof notify->dst.ip4;
	notify->cur_pos = 0;

	if (!notification_send(notify, "S", 1))
		/* when first datagram fails, next one will probably fail
		 * too */
		goto err;

	return true;

err:
	close(fd);
	notify->fd   = -1;

	return false;
}

static bool	stream_data_open(struct stream_data *s, int fd)
{
	s->fd = fd;
	s->is_eos = false;
	s->num_queued_char = 0;
	return fd >= 0;
}

static void	stream_data_close(struct stream_data *s)
{
	close(s->fd);
}
Example #21
0
error_t ariaInit(AriaContext *context, const uint8_t *key, size_t keyLength)
{
   uint_t i;
   uint32_t *ek;
   uint32_t *dk;
   const uint32_t *ck1;
   const uint32_t *ck2;
   const uint32_t *ck3;
   uint32_t w[16];

   //Check master key length
   if(keyLength != 16 && keyLength != 24 && keyLength != 32)
      return ERROR_INVALID_KEY_LENGTH;

   //First, compute 128-bit values KL and KR
   memset(w, 0, sizeof(w));
   memcpy(w, key, keyLength);

   //Save KR...
   MOV128(w + 8, w + 4);

   //128-bit master key?
   if(keyLength == 16)
   {
      //Select the relevant constants
      ck1 = c + 0;
      ck2 = c + 4;
      ck3 = c + 8;
      //The number of rounds depends on the size of the master key
      context->nr = 12;
   }
   //192-bit master key?
   else if(keyLength == 24)
   {
      //Select the relevant constants
      ck1 = c + 4;
      ck2 = c + 8;
      ck3 = c + 0;
      //The number of rounds depends on the size of the master key
      context->nr = 14;
   }
   //256-bit master key?
   else if(keyLength == 32)
   {
      //Select the relevant constants
      ck1 = c + 8;
      ck2 = c + 0;
      ck3 = c + 4;
      //The number of rounds depends on the size of the master key
      context->nr = 16;
   }

   //Compute intermediate values W0, W1, W2, and W3
   MOV128(w + 4, w + 0);
   OF(w + 4, ck1);
   XOR128(w + 4, w + 8);

   MOV128(w + 8, w + 4);
   EF(w + 8, ck2);
   XOR128(w + 8, w + 0);

   MOV128(w + 12, w + 8);
   OF(w + 12, ck3);
   XOR128(w + 12, w + 4);

   //Convert from big-endian byte order to host byte order
   for(i = 0; i < 16; i++)
      w[i] = betoh32(w[i]);

   //Point to the encryption round keys
   ek = context->ek;

   //Compute ek1, ..., ek17 as follow
   ROL128(ek + 0, w + 4, 109);
   XOR128(ek + 0, w + 0);
   ROL128(ek + 4, w + 8, 109);
   XOR128(ek + 4, w + 4);
   ROL128(ek + 8, w + 12, 109);
   XOR128(ek + 8, w + 8);
   ROL128(ek + 12, w + 0, 109);
   XOR128(ek + 12, w + 12);
   ROL128(ek + 16, w + 4, 97);
   XOR128(ek + 16, w + 0);
   ROL128(ek + 20, w + 8, 97);
   XOR128(ek + 20, w + 4);
   ROL128(ek + 24, w + 12, 97);
   XOR128(ek + 24, w + 8);
   ROL128(ek + 28, w + 0, 97);
   XOR128(ek + 28, w + 12);
   ROL128(ek + 32, w + 4, 61);
   XOR128(ek + 32, w + 0);
   ROL128(ek + 36, w + 8, 61);
   XOR128(ek + 36, w + 4);
   ROL128(ek + 40, w + 12, 61);
   XOR128(ek + 40, w + 8);
   ROL128(ek + 44, w + 0, 61);
   XOR128(ek + 44, w + 12);
   ROL128(ek + 48, w + 4, 31);
   XOR128(ek + 48, w + 0);
   ROL128(ek + 52, w + 8, 31);
   XOR128(ek + 52, w + 4);
   ROL128(ek + 56, w + 12, 31);
   XOR128(ek + 56, w + 8);
   ROL128(ek + 60, w + 0, 31);
   XOR128(ek + 60, w + 12);
   ROL128(ek + 64, w + 4, 19);
   XOR128(ek + 64, w + 0);

   //Convert from host byte order to big-endian byte order
   for(i = 0; i < 68; i++)
      ek[i] = htobe32(ek[i]);

   //Decryption round keys are derived from the encryption round keys
   dk = context->dk;
   //Compute dk1
   MOV128(dk + 0, ek + context->nr * 4);

   //Compute dk2, ..., dk(n)
   for(i = 1; i < context->nr; i++)
      A(dk + i * 4, ek + (context->nr - i) * 4);

   //Compute dk(n + 1)
   MOV128(dk + i * 4, ek + 0);

   //No error to report
   return NO_ERROR;
}
Example #22
0
void
write_file(void)
{
    FILE *fp;
    int slot;
    int block, i, fsize, fbufsize;
    struct stat st;
    char *fbuf;

    if (!quiet)
        printf("Writing file %s\n", ufilename);

    if (stat(ufilename, &st) != 0)
        err(1, "stat %s", ufilename);
    if (st.st_size == 0)
        errx(1, "%s: file is empty", vfilename);

    if (!quiet)
        printf("File %s has %lld bytes\n", ufilename, st.st_size);
    slot = -1;
    for (i = 0; i < SGI_SIZE_VOLDIR; ++i) {
        if (volhdr->voldir[i].name[0] == '\0' && slot < 0)
            slot = i;
        if (strcmp(vfilename, volhdr->voldir[i].name) == 0) {
            slot = i;
            break;
        }
    }
    if (slot == -1)
        errx(1, "no more directory entries available");
    if (betoh32(volhdr->voldir[slot].block) > 0) {
        if (!quiet)
            printf("File %s exists, removing old file\n",
                   vfilename);
        volhdr->voldir[slot].name[0] = 0;
        volhdr->voldir[slot].block = volhdr->voldir[slot].bytes = 0;
    }
    /* XXX assumes volume header starts at 0? */
    block = allocate_space((int)st.st_size);
    if (block < 0)
        errx(1, "no more space available");

    /*
     * Make sure the name in the volume header is max. 8 chars,
     * NOT including NUL.
     */
    if (strlen(vfilename) > sizeof(volhdr->voldir[slot].name))
        warnx("%s: filename is too long and will be truncated",
              vfilename);
    strncpy(volhdr->voldir[slot].name, vfilename,
            sizeof(volhdr->voldir[slot].name));

    volhdr->voldir[slot].block = htobe32(block);
    volhdr->voldir[slot].bytes = htobe32(st.st_size);

    write_volhdr();

    /* Write the file itself. */
    if (lseek(fd, block * DEV_BSIZE, SEEK_SET) == -1)
        err(1, "lseek write");
    fbufsize = volhdr->dp.dp_secbytes;
    if ((fbuf = malloc(fbufsize)) == NULL)
        err(1, "failed to allocate buffer");
    i = st.st_size;
    fp = fopen(ufilename, "r");
    while (i > 0) {
        bzero(fbuf, fbufsize);
        fsize = i > fbufsize ? fbufsize : i;
        if (fread(fbuf, 1, fsize, fp) != fsize)
            err(1, "reading file from disk");
        if (write(fd, fbuf, fbufsize) != fbufsize)
            err(1, "writing file to SGI volume header");
        i -= fsize;
    }
    fclose(fp);
    free(fbuf);
}
Example #23
0
static int
alloc_nm_rxq_hwq(struct port_info *pi, struct sge_nm_rxq *nm_rxq)
{
	int rc, cntxt_id;
	__be32 v;
	struct adapter *sc = pi->adapter;
	struct netmap_adapter *na = NA(pi->nm_ifp);
	struct fw_iq_cmd c;

	MPASS(na != NULL);
	MPASS(nm_rxq->iq_desc != NULL);
	MPASS(nm_rxq->fl_desc != NULL);

	bzero(nm_rxq->iq_desc, pi->qsize_rxq * IQ_ESIZE);
	bzero(nm_rxq->fl_desc, na->num_rx_desc * EQ_ESIZE + spg_len);

	bzero(&c, sizeof(c));
	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_IQ_CMD) | F_FW_CMD_REQUEST |
	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_IQ_CMD_PFN(sc->pf) |
	    V_FW_IQ_CMD_VFN(0));
	c.alloc_to_len16 = htobe32(F_FW_IQ_CMD_ALLOC | F_FW_IQ_CMD_IQSTART |
	    FW_LEN16(c));
	if (pi->flags & INTR_NM_RXQ) {
		KASSERT(nm_rxq->intr_idx < sc->intr_count,
		    ("%s: invalid direct intr_idx %d", __func__,
		    nm_rxq->intr_idx));
		v = V_FW_IQ_CMD_IQANDSTINDEX(nm_rxq->intr_idx);
	} else {
		CXGBE_UNIMPLEMENTED(__func__);	/* XXXNM: needs review */
		v = V_FW_IQ_CMD_IQANDSTINDEX(nm_rxq->intr_idx) |
		    F_FW_IQ_CMD_IQANDST;
	}
	c.type_to_iqandstindex = htobe32(v |
	    V_FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
	    V_FW_IQ_CMD_VIID(pi->nm_viid) |
	    V_FW_IQ_CMD_IQANUD(X_UPDATEDELIVERY_INTERRUPT));
	c.iqdroprss_to_iqesize = htobe16(V_FW_IQ_CMD_IQPCIECH(pi->tx_chan) |
	    F_FW_IQ_CMD_IQGTSMODE |
	    V_FW_IQ_CMD_IQINTCNTTHRESH(0) |
	    V_FW_IQ_CMD_IQESIZE(ilog2(IQ_ESIZE) - 4));
	c.iqsize = htobe16(pi->qsize_rxq);
	c.iqaddr = htobe64(nm_rxq->iq_ba);
	c.iqns_to_fl0congen |=
	    htobe32(V_FW_IQ_CMD_FL0HOSTFCMODE(X_HOSTFCMODE_NONE) |
		F_FW_IQ_CMD_FL0FETCHRO | F_FW_IQ_CMD_FL0DATARO |
		(fl_pad ? F_FW_IQ_CMD_FL0PADEN : 0));
	c.fl0dcaen_to_fl0cidxfthresh =
	    htobe16(V_FW_IQ_CMD_FL0FBMIN(X_FETCHBURSTMIN_64B) |
		V_FW_IQ_CMD_FL0FBMAX(X_FETCHBURSTMAX_512B));
	c.fl0size = htobe16(na->num_rx_desc + spg_len / EQ_ESIZE);
	c.fl0addr = htobe64(nm_rxq->fl_ba);

	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
	if (rc != 0) {
		device_printf(sc->dev,
		    "failed to create netmap ingress queue: %d\n", rc);
		return (rc);
	}

	nm_rxq->iq_cidx = 0;
	MPASS(nm_rxq->iq_sidx == pi->qsize_rxq - spg_len / IQ_ESIZE);
	nm_rxq->iq_gen = F_RSPD_GEN;
	nm_rxq->iq_cntxt_id = be16toh(c.iqid);
	nm_rxq->iq_abs_id = be16toh(c.physiqid);
	cntxt_id = nm_rxq->iq_cntxt_id - sc->sge.iq_start;
	if (cntxt_id >= sc->sge.niq) {
		panic ("%s: nm_rxq->iq_cntxt_id (%d) more than the max (%d)",
		    __func__, cntxt_id, sc->sge.niq - 1);
	}
	sc->sge.iqmap[cntxt_id] = (void *)nm_rxq;

	nm_rxq->fl_cntxt_id = be16toh(c.fl0id);
	nm_rxq->fl_pidx = nm_rxq->fl_cidx = 0;
	MPASS(nm_rxq->fl_sidx == na->num_rx_desc);
	cntxt_id = nm_rxq->fl_cntxt_id - sc->sge.eq_start;
	if (cntxt_id >= sc->sge.neq) {
		panic("%s: nm_rxq->fl_cntxt_id (%d) more than the max (%d)",
		    __func__, cntxt_id, sc->sge.neq - 1);
	}
	sc->sge.eqmap[cntxt_id] = (void *)nm_rxq;

	nm_rxq->fl_db_val = F_DBPRIO | V_QID(nm_rxq->fl_cntxt_id) | V_PIDX(0);
	if (is_t5(sc))
		nm_rxq->fl_db_val |= F_DBTYPE;

	t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS), V_SEINTARM(F_QINTR_CNT_EN) |
	    V_INGRESSQID(nm_rxq->iq_cntxt_id));

	return (rc);
}
Example #24
0
/*
 * main:
 *	Drive the sucker.  There are two main modes -- either we store
 *	the seek pointers, if the table is to be sorted or randomized,
 *	or we write the pointer directly to the file, if we are to stay
 *	in file order.  If the former, we allocate and re-allocate in
 *	CHUNKSIZE blocks; if the latter, we just write each pointer,
 *	and then seek back to the beginning to write in the table.
 */
int
main(int ac, char *av[])
{
    char *sp, *nsp, dc;
    FILE *inf, *outf;
    off_t last_off, pos, *p;
    size_t length;
    int first;
    uint32_t cnt;
    STR *fp;
    static char string[257];

    setlocale(LC_ALL, "");

    getargs(ac, av);		/* evalute arguments */
    dc = Delimch;
    if ((inf = fopen(Infile, "r")) == NULL) {
        perror(Infile);
        exit(1);
    }

    if ((outf = fopen(Outfile, "w")) == NULL) {
        perror(Outfile);
        exit(1);
    }
    if (!STORING_PTRS)
        fseek(outf, (long)sizeof(Tbl), SEEK_SET);

    /*
     * Write the strings onto the file
     */

    Tbl.str_longlen = 0;
    Tbl.str_shortlen = 0xffffffff;
    Tbl.str_delim = dc;
    Tbl.str_version = VERSION;
    first = Oflag;
    add_offset(outf, ftello(inf));
    last_off = 0;
    do {
        sp = fgets(string, 256, inf);
        if (sp == NULL || (sp[0] == dc && sp[1] == '\n')) {
            pos = ftello(inf);
            length = (size_t)(pos - last_off) -
                     (sp != NULL ? strlen(sp) : 0);
            last_off = pos;
            if (length == 0)
                continue;
            add_offset(outf, pos);
            if ((size_t)Tbl.str_longlen < length)
                Tbl.str_longlen = length;
            if ((size_t)Tbl.str_shortlen > length)
                Tbl.str_shortlen = length;
            first = Oflag;
        }
        else if (first) {
            for (nsp = sp; !isalnum((unsigned char)*nsp); nsp++)
                continue;
            ALLOC(Firstch, Num_pts);
            fp = &Firstch[Num_pts - 1];
            if (Iflag && isupper((unsigned char)*nsp))
                fp->first = tolower((unsigned char)*nsp);
            else
                fp->first = *nsp;
            fp->pos = Seekpts[Num_pts - 1];
            first = false;
        }
    } while (sp != NULL);

    /*
     * write the tables in
     */

    fclose(inf);
    Tbl.str_numstr = Num_pts - 1;

    if (Cflag)
        Tbl.str_flags |= STR_COMMENTS;

    if (Oflag)
        do_order();
    else if (Rflag)
        randomize();

    if (Xflag)
        Tbl.str_flags |= STR_ROTATED;

    if (!Sflag) {
        printf("\"%s\" created\n", Outfile);
        if (Num_pts == 2)
            puts("There was 1 string");
        else
            printf("There were %u strings\n", Num_pts - 1);
        printf("Longest string: %u byte%s\n", Tbl.str_longlen,
               Tbl.str_longlen == 1 ? "" : "s");
        printf("Shortest string: %u byte%s\n", Tbl.str_shortlen,
               Tbl.str_shortlen == 1 ? "" : "s");
    }

    rewind(outf);
    Tbl.str_version = htobe32(Tbl.str_version);
    Tbl.str_numstr = htobe32(Tbl.str_numstr);
    Tbl.str_longlen = htobe32(Tbl.str_longlen);
    Tbl.str_shortlen = htobe32(Tbl.str_shortlen);
    Tbl.str_flags = htobe32(Tbl.str_flags);
    fwrite((char *)&Tbl, sizeof(Tbl), 1, outf);
    if (STORING_PTRS) {
        for (p = Seekpts, cnt = Num_pts; cnt--; ++p)
            *p = htobe64(*p);
        fwrite(Seekpts, sizeof(*Seekpts), (size_t)Num_pts, outf);
    }
    fclose(outf);
    exit(0);
}
Example #25
0
// enlarges (reallocates) container and copies dd level block into container
int p9_dd_add(
    uint8_t** io_cont, uint32_t* o_cont_size, uint8_t i_dd,
    uint8_t* i_buf, uint32_t i_buf_size)
{
    struct p9_dd_cont*  cont = (struct p9_dd_cont*)*io_cont;

    uint8_t*            dupl_buf;
    uint32_t            dupl_size;

    uint32_t            enlarged;

    int                 rc;

    uint8_t*            others_addr_new;
    uint8_t*            others_addr_old;
    uint32_t            others_size;
    struct p9_dd_block* others_block;

    uint8_t*            this_addr;
    uint32_t            this_offs;
    struct p9_dd_block* this_block;

    struct p9_dd_iter   iter = P9_DD_ITER_INIT(NULL);

    // handle duplicates and initial setup of empty container
    rc = p9_dd_get(*io_cont, i_dd, &dupl_buf, &dupl_size);

    switch (rc)
    {
        case P9_DD_FAILURE_NOT_FOUND :
            break;

        case P9_DD_FAILURE_DOES_NOT_EXIST :
            cont = p9_dd_create();

            if (!cont)
            {
                return P9_DD_FAILURE_NOMEM;
            }

            break;

        case P9_DD_SUCCESS :
            return P9_DD_FAILURE_DUPLICATE;

        default :
            return rc;
    }

    // size of enlarged container
    enlarged = p9_dd_size(cont) + sizeof(struct p9_dd_block) + i_buf_size;

    // re-allocate to enlarge container (content is retained and consistent)
    cont = (struct p9_dd_cont*)realloc(cont, enlarged);

    if (!cont)
    {
        return P9_DD_FAILURE_NOMEM;
    }

    // offsets and size of existing bufs
    others_addr_old = p9_dd_addr(cont, p9_dd_size_meta(cont));
    others_addr_new = others_addr_old + sizeof(struct p9_dd_block);
    others_size     = p9_dd_size(cont) - p9_dd_size_meta(cont);

    // meta data, offset and address of new buf
    this_block = (struct p9_dd_block*)others_addr_old;
    this_offs  = p9_dd_size(cont) + sizeof(struct p9_dd_block);
    this_addr  = p9_dd_addr(cont, this_offs);

    // fix offsets of existing bufs
    iter.iv_cont = cont;

    while ((others_block = p9_dd_next(&iter)))
    {
        others_block->iv_offset =
            htobe32(be32toh(others_block->iv_offset) +
                    sizeof(struct p9_dd_block));
    }

    // move existing bufs
    memmove(others_addr_new, others_addr_old, others_size);

    // copy new buf into container
    memcpy(this_addr, i_buf, i_buf_size);

    // fill in meta data for new buf
    memset(this_block, sizeof(struct p9_dd_block), 0);
    this_block->iv_offset = htobe32(this_offs);
    this_block->iv_size   = htobe32(i_buf_size);
    this_block->iv_dd     = i_dd;
    this_block->iv_reserved[0] = 0;
    this_block->iv_reserved[1] = 0;
    this_block->iv_reserved[2] = 0;

    // increase number off DD level blocks in container
    (cont)->iv_num++;

    *io_cont = (uint8_t*)cont;
    *o_cont_size = enlarged;

    return P9_DD_SUCCESS;
}
Example #26
0
int
do_test (void)
{
  int result = 0;

  for (uint64_t i = 0; i < (~UINT64_C (0)) >> 2; i = (i << 1) + 3)
    {
      if (i < UINT64_C (65536))
	{
	  DIAG_PUSH_NEEDS_COMMENT;
	  DIAG_IGNORE_NEEDS_COMMENT_TAUTOLOGICAL_COMPARE ();
	  if (htobe16 (be16toh (i)) != i)
	    {
	      printf ("htobe16 (be16toh (%" PRIx64 ")) == %" PRIx16 "\n",
		      i, (uint16_t) htobe16 (be16toh (i)));
	      result = 1;
	    }
	  if (htole16 (le16toh (i)) != i)
	    {
	      printf ("htole16 (le16toh (%" PRIx64 ")) == %" PRIx16 "\n",
		      i, (uint16_t) htole16 (le16toh (i)));
	      result = 1;
	    }
	  DIAG_POP_NEEDS_COMMENT;

	  uint16_t n[2];
	  n[__BYTE_ORDER == __LITTLE_ENDIAN] = bswap_16 (i);
	  n[__BYTE_ORDER == __BIG_ENDIAN] = i;
	  if (htole16 (i) != n[0])
	    {
	      printf ("htole16 (%" PRIx64 ") == %" PRIx16 " != %" PRIx16 "\n",
		      i, (uint16_t) htole16 (i), n[0]);
	      result = 1;
	    }
	  if (htobe16 (i) != n[1])
	    {
	      printf ("htobe16 (%" PRIx64 ") == %" PRIx16 " != %" PRIx16 "\n",
		      i, (uint16_t) htobe16 (i), n[1]);
	      result = 1;
	    }
	}

      if (i < UINT64_C (4294967296))
	{
	  DIAG_PUSH_NEEDS_COMMENT;
	  DIAG_IGNORE_NEEDS_COMMENT_TAUTOLOGICAL_COMPARE ();
	  if (htobe32 (be32toh (i)) != i)
	    {
	      printf ("htobe32 (be32toh (%" PRIx64 ")) == %" PRIx32 "\n",
		      i, (uint32_t) htobe32 (be32toh (i)));
	      result = 1;
	    }
	  if (htole32 (le32toh (i)) != i)
	    {
	      printf ("htole32 (le32toh (%" PRIx64 ")) == %" PRIx32 "\n",
		      i, (uint32_t) htole32 (le32toh (i)));
	      result = 1;
	    }
	  DIAG_POP_NEEDS_COMMENT;

	  uint32_t n[2];
	  n[__BYTE_ORDER == __LITTLE_ENDIAN] = bswap_32 (i);
	  n[__BYTE_ORDER == __BIG_ENDIAN] = i;
	  if (htole32 (i) != n[0])
	    {
	      printf ("htole32 (%" PRIx64 ") == %" PRIx32 " != %" PRIx32 "\n",
		      i, (uint32_t) htole32 (i), n[0]);
	      result = 1;
	    }
	  if (htobe32 (i) != n[1])
	    {
	      printf ("htobe32 (%" PRIx64 ") == %" PRIx32 " != %" PRIx32 "\n",
		      i, (uint32_t) htobe32 (i), n[1]);
	      result = 1;
	    }
	}

      DIAG_PUSH_NEEDS_COMMENT;
      DIAG_IGNORE_NEEDS_COMMENT_TAUTOLOGICAL_COMPARE ();
      if (htobe64 (be64toh (i)) != i)
	{
	  printf ("htobe64 (be64toh (%" PRIx64 ")) == %" PRIx64 "\n",
		  i, htobe64 (be64toh (i)));
	  result = 1;
	}
      if (htole64 (le64toh (i)) != i)
	{
	  printf ("htole64 (le64toh (%" PRIx64 ")) == %" PRIx64 "\n",
		  i, htole64 (le64toh (i)));
	  result = 1;
	}
      DIAG_POP_NEEDS_COMMENT;

      uint64_t n[2];
      n[__BYTE_ORDER == __LITTLE_ENDIAN] = bswap_64 (i);
      n[__BYTE_ORDER == __BIG_ENDIAN] = i;
      if (htole64 (i) != n[0])
	{
	  printf ("htole64 (%" PRIx64 ") == %" PRIx64 " != %" PRIx64 "\n",
		  i, htole64 (i), n[0]);
	  result = 1;
	}
      if (htobe64 (i) != n[1])
	{
	  printf ("htobe64 (%" PRIx64 ") == %" PRIx64 " != %" PRIx64 "\n",
		  i, htobe64 (i), n[1]);
	  result = 1;
	}
    }

  return result;
}
Example #27
0
int main(int argc, char **argv)
{
    int ch, fd, do_reloc = 0;
    uint32_t hunk_id, insz, outsz, i, x, first, last;
    uint32_t *hunk_offs, cur = 0;
    char *in, *out, *p, *buf, *outbuf;
    uint32_t base = 0;
    const static char *typename[] = { "Any", "Chip", "Fast", "Reserved" };
    const static char *hunkname[] = { "HUNK_CODE", "HUNK_DATA", "HUNK_BSS" };
    int seen_dat;

    const static char sopts[] = "hb:r";
    const static struct option lopts[] = {
        { "help", 0, NULL, 'h' },
        { "base", 1, NULL, 'b' },
        { "reloc", 0, NULL, 'r' },
        { 0, 0, 0, 0 }
    };

    while ((ch = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
        switch (ch) {
        case 'h':
            usage(0);
            break;
        case 'b':
            base = strtol(optarg, NULL, 16);
            break;
        case 'r':
            do_reloc = 1;
            break;
        default:
            usage(1);
            break;
        }
    }

    if (argc != (optind + 2))
        usage(1);
    in = argv[optind];
    out = argv[optind+1];

    fd = open(in, O_RDONLY);
    if (fd == -1)
        err(1, "%s", in);
    if ((insz = lseek(fd, 0, SEEK_END)) < 0)
        err(1, NULL);
    lseek(fd, 0, SEEK_SET);
    if ((buf = malloc(insz)) == NULL)
        err(1, NULL);
    if (read(fd, buf, insz) != insz)
        err(1, NULL);
    close(fd);
    p = buf;

    hunk_id = fetch32(&p);
    if (hunk_id != HUNK_HEADER)
        goto bad_hunk;
    printf("HUNK_HEADER\n");
    x = fetch32(&p);
    if (x)
        goto bad_hunk;
    x = fetch32(&p);
    first = fetch32(&p);
    last = fetch32(&p);
    if (first || (x != (last+1-first))) {
        /* For sanity's sake we expect only loadable hunks, numbered 0..N-1. */
        printf(" Table size: %u, First: %u, Last: %u\n", x, first, last);
        goto bad_hunk;
    }
    hunk_offs = malloc(x * sizeof(*hunk_offs));
    memset(hunk_offs, 0, x * sizeof(*hunk_offs));
    hunk_offs[0] = base;
    for (i = first; i <= last; i++) {
        uint8_t type;
        x = fetch32(&p);
        type = x >> 30;
        x &= (1u<<30)-1;
        if (type >= 3) {
            /* We don't support extended AllocMem flags (type=3) */
            printf("Bad hunk AllocFlag %u\n", type);
            goto bad_hunk;
        }
        printf("  Hunk %u: %u longwords (%s)\n", i, x, typename[type]);
        /* Real Amiga loader would AllocMem() here. */
        hunk_offs[i+1] = hunk_offs[i] + 4*x;
    }
    outsz = hunk_offs[i];
    outbuf = malloc(outsz);
    
    cur = seen_dat = 0;
    while ((p - buf) < insz) {
        hunk_id = fetch32(&p) & ((1u<<30)-1);
        switch (hunk_id) {
        case HUNK_CODE:
        case HUNK_DATA:
        case HUNK_BSS:
            if (seen_dat)
                cur++;
            seen_dat = 1;
            printf("\n%s [Hunk %u]\n", hunkname[hunk_id-HUNK_CODE], cur);
            x = fetch32(&p);
            printf("  %u longwords\n", x);
            if (hunk_id == HUNK_BSS) {
                memset(outbuf + hunk_offs[cur] - base, 0, 4*x);
            } else {
                memcpy(outbuf + hunk_offs[cur] - base, p, 4*x);
                p += 4*x;
            }
            break;
        case HUNK_RELOC32: {
            uint32_t nr, id;
            printf("HUNK_RELOC32\n");
            while ((nr = fetch32(&p)) != 0) {
                id = fetch32(&p);
                printf("  Hunk %u: %u offsets\n", id, nr);
                for (i = 0; i < nr; i++) {
                    x = fetch32(&p);
                    if (do_reloc) {
                        uint32_t *pp = (uint32_t *)(outbuf + hunk_offs[cur]
                                                    + x - base);
                        *pp = htobe32(be32toh(*pp) + hunk_offs[id]);
                    }
                }
            }
            break;
        }
        case HUNK_END:
            printf("HUNK_END\n");
            if (!seen_dat) {
                printf("Premature HUNK_END\n");
                goto bad_hunk;
            }
            cur++;
            seen_dat = 0;
            break;
        default:
            printf("%08x - UNKNOWN\n", hunk_id);
            goto bad_hunk;
        }
    }

    if (cur != (last+1))
        goto bad_hunk;

    fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644);
    if (fd == -1)
        err(1, "%s", out);
    if (write(fd, outbuf, outsz) != outsz)
        err(1, NULL);
    close(fd);

    return 0;

bad_hunk:
    printf("ERROR_BAD_HUNK\n");
    return 1;
}
Example #28
0
static int test_advertise_option(sd_event *e) {
        _cleanup_(sd_dhcp6_lease_unrefp) sd_dhcp6_lease *lease = NULL;
        DHCP6Message *advertise = (DHCP6Message *)msg_advertise;
        uint8_t *optval, *opt = msg_advertise + sizeof(DHCP6Message);
        uint16_t optcode;
        size_t optlen, len = sizeof(msg_advertise) - sizeof(DHCP6Message);
        be32_t val;
        uint8_t preference = 255;
        struct in6_addr addr;
        uint32_t lt_pref, lt_valid;
        int r;
        bool opt_clientid = false;
        struct in6_addr *addrs;
        char **domains;

        if (verbose)
                printf("* %s\n", __FUNCTION__);

        assert_se(dhcp6_lease_new(&lease) >= 0);

        assert_se(advertise->type == DHCP6_ADVERTISE);
        assert_se((be32toh(advertise->transaction_id) & 0x00ffffff) ==
                  0x0fb4e5);

        while ((r = dhcp6_option_parse(&opt, &len, &optcode, &optlen,
                                       &optval)) >= 0) {

                switch(optcode) {
                case SD_DHCP6_OPTION_CLIENTID:
                        assert_se(optlen == 14);

                        opt_clientid = true;
                        break;

                case SD_DHCP6_OPTION_IA_NA:
                        assert_se(optlen == 94);
                        assert_se(!memcmp(optval, &msg_advertise[26], optlen));

                        val = htobe32(0x0ecfa37d);
                        assert_se(!memcmp(optval, &val, sizeof(val)));

                        val = htobe32(80);
                        assert_se(!memcmp(optval + 4, &val, sizeof(val)));

                        val = htobe32(120);
                        assert_se(!memcmp(optval + 8, &val, sizeof(val)));

                        assert_se(dhcp6_option_parse_ia(&optval, &optlen,
                                                        optcode,
                                                        &lease->ia) >= 0);

                        break;

                case SD_DHCP6_OPTION_SERVERID:
                        assert_se(optlen == 14);
                        assert_se(!memcmp(optval, &msg_advertise[179], optlen));

                        assert_se(dhcp6_lease_set_serverid(lease, optval,
                                                           optlen) >= 0);
                        break;

                case SD_DHCP6_OPTION_PREFERENCE:
                        assert_se(optlen == 1);
                        assert_se(!*optval);

                        assert_se(dhcp6_lease_set_preference(lease,
                                                             *optval) >= 0);
                        break;

                case SD_DHCP6_OPTION_ELAPSED_TIME:
                        assert_se(optlen == 2);

                        break;

                case SD_DHCP6_OPTION_DNS_SERVERS:
                        assert_se(optlen == 16);
                        assert_se(dhcp6_lease_set_dns(lease, optval,
                                                      optlen) >= 0);
                        break;

                case SD_DHCP6_OPTION_DOMAIN_LIST:
                        assert_se(optlen == 11);
                        assert_se(dhcp6_lease_set_domains(lease, optval,
                                                          optlen) >= 0);
                        break;

                case SD_DHCP6_OPTION_SNTP_SERVERS:
                        assert_se(optlen == 16);
                        assert_se(dhcp6_lease_set_sntp(lease, optval,
                                                       optlen) >= 0);
                        break;

                default:
                        break;
                }
        }


        assert_se(r == -ENOMSG);

        assert_se(opt_clientid);

        sd_dhcp6_lease_reset_address_iter(lease);
        assert_se(sd_dhcp6_lease_get_address(lease, &addr, &lt_pref,
                                             &lt_valid) >= 0);
        assert_se(!memcmp(&addr, &msg_advertise[42], sizeof(addr)));
        assert_se(lt_pref == 150);
        assert_se(lt_valid == 180);
        assert_se(sd_dhcp6_lease_get_address(lease, &addr, &lt_pref,
                                             &lt_valid) == -ENOMSG);

        sd_dhcp6_lease_reset_address_iter(lease);
        assert_se(sd_dhcp6_lease_get_address(lease, &addr, &lt_pref,
                                             &lt_valid) >= 0);
        assert_se(!memcmp(&addr, &msg_advertise[42], sizeof(addr)));
        assert_se(sd_dhcp6_lease_get_address(lease, &addr, &lt_pref,
                                             &lt_valid) == -ENOMSG);
        sd_dhcp6_lease_reset_address_iter(lease);
        assert_se(sd_dhcp6_lease_get_address(lease, &addr, &lt_pref,
                                             &lt_valid) >= 0);
        assert_se(!memcmp(&addr, &msg_advertise[42], sizeof(addr)));
        assert_se(sd_dhcp6_lease_get_address(lease, &addr, &lt_pref,
                                             &lt_valid) == -ENOMSG);

        assert_se(dhcp6_lease_get_serverid(lease, &opt, &len) >= 0);
        assert_se(len == 14);
        assert_se(!memcmp(opt, &msg_advertise[179], len));

        assert_se(dhcp6_lease_get_preference(lease, &preference) >= 0);
        assert_se(preference == 0);

        r = sd_dhcp6_lease_get_dns(lease, &addrs);
        assert_se(r == 1);
        assert_se(!memcmp(addrs, &msg_advertise[124], r * 16));

        r = sd_dhcp6_lease_get_domains(lease, &domains);
        assert_se(r == 1);
        assert_se(!strcmp("lab.intra", domains[0]));
        assert_se(domains[1] == NULL);

        r = sd_dhcp6_lease_get_ntp_addrs(lease, &addrs);
        assert_se(r == 1);
        assert_se(!memcmp(addrs, &msg_advertise[159], r * 16));

        return 0;
}
/*
 * Old Format:
 *	sector 0:	LIF volume header (40 bytes)
 *	sector 1:	<unused>
 *	sector 2:	LIF directory (8 x 32 == 256 bytes)
 *	sector 3-:	LIF file 0, LIF file 1, etc.
 * where sectors are 256 bytes.
 *
 * New Format:
 *	sector 0:	LIF volume header (40 bytes)
 *	sector 1:	<unused>
 *	sector 2:	LIF directory (8 x 32 == 256 bytes)
 *	sector 3:	<unused>
 *	sector 4-31:	disklabel (~300 bytes right now)
 *	sector 32-:	LIF file 0, LIF file 1, etc.
 */
int
main(int argc, char **argv)
{
	char *n1, *n2, *n3;
	int n, to;
	int count;

	--argc;
	++argv;
	if (argc == 0)
		usage();
	if (!strcmp(argv[0], "-l")) {
		argv++;
		argc--;
		if (argc == 0)
			usage();
		sscanf(argv[0], "0x%x", &loadpoint);
		lpflag++;
		argv++;
		argc--;
	}
	if (!lpflag || argc == 0)
		usage();
	n1 = argv[0];
	argv++;
	argc--;
	if (argc == 0)
		usage();
	if (argc > 1) {
		n2 = argv[0];
		argv++;
		argc--;
		if (argc > 1) {
			n3 = argv[0];
			argv++;
			argc--;
		} else
			n3 = NULL;
	} else
		n2 = n3 = NULL;

	to = open(argv[0], O_WRONLY | O_TRUNC | O_CREAT, 0644);
	if (to < 0) {
		perror("open");
		exit(1);
	}
	/* clear possibly unused directory entries */
	strncpy(lifd[1].dir_name, "          ", 10);
	lifd[1].dir_type = htobe16(-1);
	lifd[1].dir_addr = htobe32(0);
	lifd[1].dir_length = htobe32(0);
	lifd[1].dir_flag = htobe16(0xFF);
	lifd[1].dir_exec = htobe32(0);
	lifd[7] = lifd[6] = lifd[5] = lifd[4] = lifd[3] = lifd[2] = lifd[1];
	/* record volume info */
	lifv.vol_id = htobe16(VOL_ID);
	strncpy(lifv.vol_label, "BOOT43", 6);
	lifv.vol_addr = htobe32(btolifs(LIF_DIRSTART));
	lifv.vol_oct = htobe16(VOL_OCT);
	lifv.vol_dirsize = htobe32(btolifs(LIF_DIRSIZE));
	lifv.vol_version = htobe16(1);
	/* output bootfile one */
	lseek(to, LIF_FILESTART, SEEK_SET);
	count = putfile(n1, to);
	n = btolifs(count);
	strcpy(lifd[0].dir_name, lifname(n1));
	lifd[0].dir_type = htobe16(DIR_TYPE);
	lifd[0].dir_addr = htobe32(btolifs(LIF_FILESTART));
	lifd[0].dir_length = htobe32(n);
	bcddate(n1, lifd[0].dir_toc);
	lifd[0].dir_flag = htobe16(DIR_FLAG);
	lifd[0].dir_exec = htobe32(loadpoint);
	lifv.vol_length = htobe32(be32toh(lifd[0].dir_addr) +
				  be32toh(lifd[0].dir_length));
	/* if there is an optional second boot program, output it */
	if (n2) {
		lseek(to, LIF_FILESTART+lifstob(n), SEEK_SET);
		count = putfile(n2, to);
		n = btolifs(count);
		strcpy(lifd[1].dir_name, lifname(n2));
		lifd[1].dir_type = htobe16(DIR_TYPE);
		lifd[1].dir_addr = htobe32(lifv.vol_length);
		lifd[1].dir_length = htobe32(n);
		bcddate(n2, lifd[1].dir_toc);
		lifd[1].dir_flag = htobe16(DIR_FLAG);
		lifd[1].dir_exec = htobe32(loadpoint);
		lifv.vol_length = htobe32(be32toh(lifd[1].dir_addr) +
					  be32toh(lifd[1].dir_length));
	}
	/* ditto for three */
	if (n3) {
		lseek(to, LIF_FILESTART+lifstob(lifd[0].dir_length+n),
		      SEEK_SET);
		count = putfile(n3, to);
		n = btolifs(count);
		strcpy(lifd[2].dir_name, lifname(n3));
		lifd[2].dir_type = htobe16(DIR_TYPE);
		lifd[2].dir_addr = htobe32(lifv.vol_length);
		lifd[2].dir_length = htobe32(n);
		bcddate(n3, lifd[2].dir_toc);
		lifd[2].dir_flag = htobe16(DIR_FLAG);
		lifd[2].dir_exec = htobe32(loadpoint);
		lifv.vol_length = htobe32(be32toh(lifd[2].dir_addr) +
					  be32toh(lifd[2].dir_length));
	}
	/* output volume/directory header info */
	lseek(to, LIF_VOLSTART, SEEK_SET);
	write(to, &lifv, LIF_VOLSIZE);
	lseek(to, LIF_DIRSTART, SEEK_SET);
	write(to, lifd, LIF_DIRSIZE);
	exit(0);
}
Example #30
0
struct quotafile *
quota_open(struct fstab *fs, int quotatype, int openflags)
{
	struct quotafile *qf;
	struct dqhdr64 dqh;
	struct group *grp;
	struct stat st;
	int qcmd, serrno;

	if (strcmp(fs->fs_vfstype, "ufs"))
		return (NULL);
	if ((qf = calloc(1, sizeof(*qf))) == NULL)
		return (NULL);
	qf->fd = -1;
	qf->quotatype = quotatype;
	strncpy(qf->fsname, fs->fs_file, sizeof(qf->fsname));
	if (stat(qf->fsname, &st) != 0)
		goto error;
	qf->dev = st.st_dev;
	serrno = hasquota(fs, quotatype, qf->qfname, sizeof(qf->qfname));
	qcmd = QCMD(Q_GETQUOTASIZE, quotatype);
	if (quotactl(qf->fsname, qcmd, 0, &qf->wordsize) == 0)
		return (qf);
	if (serrno == 0) {
		errno = EOPNOTSUPP;
		goto error;
	}
	qf->accmode = openflags & O_ACCMODE;
	if ((qf->fd = open(qf->qfname, qf->accmode)) < 0 &&
	    (openflags & O_CREAT) != O_CREAT)
		goto error;
	/* File open worked, so process it */
	if (qf->fd != -1) {
		qf->wordsize = 32;
		switch (read(qf->fd, &dqh, sizeof(dqh))) {
		case -1:
			goto error;
		case sizeof(dqh):
			if (strcmp(dqh.dqh_magic, Q_DQHDR64_MAGIC) != 0) {
				/* no magic, assume 32 bits */
				qf->wordsize = 32;
				return (qf);
			}
			if (be32toh(dqh.dqh_version) != Q_DQHDR64_VERSION ||
			    be32toh(dqh.dqh_hdrlen) != sizeof(struct dqhdr64) ||
			    be32toh(dqh.dqh_reclen) != sizeof(struct dqblk64)) {
				/* correct magic, wrong version / lengths */
				errno = EINVAL;
				goto error;
			}
			qf->wordsize = 64;
			return (qf);
		default:
			qf->wordsize = 32;
			return (qf);
		}
		/* not reached */
	}
	/* open failed, but O_CREAT was specified, so create a new file */
	if ((qf->fd = open(qf->qfname, O_RDWR|O_CREAT|O_TRUNC, 0)) < 0)
		goto error;
	qf->wordsize = 64;
	memset(&dqh, 0, sizeof(dqh));
	memcpy(dqh.dqh_magic, Q_DQHDR64_MAGIC, sizeof(dqh.dqh_magic));
	dqh.dqh_version = htobe32(Q_DQHDR64_VERSION);
	dqh.dqh_hdrlen = htobe32(sizeof(struct dqhdr64));
	dqh.dqh_reclen = htobe32(sizeof(struct dqblk64));
	if (write(qf->fd, &dqh, sizeof(dqh)) != sizeof(dqh)) {
		/* it was one we created ourselves */
		unlink(qf->qfname);
		goto error;
	}
	grp = getgrnam(QUOTAGROUP);
	fchown(qf->fd, 0, grp ? grp->gr_gid : 0);
	fchmod(qf->fd, 0640);
	return (qf);
error:
	serrno = errno;
	/* did we have an open file? */
	if (qf->fd != -1)
		close(qf->fd);
	free(qf);
	errno = serrno;
	return (NULL);
}