Example #1
0
File: zbuf.c Project: d4s/nmsg
nmsg_res
nmsg_zbuf_deflate(nmsg_zbuf_t zb, size_t len, u_char *buf,
		  size_t *z_len, u_char *z_buf)
{
	int zret;

	store_net32(z_buf, (uint32_t) len);
	z_buf += 4;

	zb->zs.avail_in = len;
	zb->zs.next_in = buf;
	zb->zs.avail_out = *z_len;
	zb->zs.next_out = z_buf;

	zret = deflate(&zb->zs, Z_FINISH);
	assert(zret == Z_STREAM_END);
	assert(zb->zs.avail_in == 0);
	*z_len = *z_len - zb->zs.avail_out + sizeof(uint32_t);
	assert(deflateReset(&zb->zs) == Z_OK);
	assert(*z_len > 0);

	return (nmsg_res_success);
}
Example #2
0
nmsg_res
nmsg_container_serialize(struct nmsg_container *c,
			 uint8_t **pbuf, size_t *buf_len,
			 bool do_header, bool do_zlib,
			 uint32_t sequence, uint64_t sequence_id)
{
	static const char magic[] = NMSG_MAGIC;
	size_t len = 0;
	uint8_t flags;
	uint8_t *buf;
	uint8_t *len_wire = NULL;
	uint16_t version;

	*pbuf = buf = malloc((do_zlib) ? (2 * c->estsz) : (c->estsz));
	if (buf == NULL)
		return (nmsg_res_memfail);

	if (do_header) {
		/* serialize header */
		memcpy(buf, magic, sizeof(magic));
		buf += sizeof(magic);
		flags = (do_zlib) ? NMSG_FLAG_ZLIB : 0;
		version = NMSG_VERSION | (flags << 8);
		version = htons(version);
		memcpy(buf, &version, sizeof(version));
		buf += sizeof(version);
		
		/* save location where length of serialized NMSG container will be written */
		len_wire = buf;
		buf += sizeof(uint32_t);
	}

	/* calculate payload CRCs */
	_nmsg_payload_calc_crcs(c->nmsg);

	if (c->do_sequence) {
		c->nmsg->sequence = sequence;
		c->nmsg->sequence_id = sequence_id;
		c->nmsg->has_sequence = true;
		c->nmsg->has_sequence_id = true;
	}

	/* serialize the container */
	if (do_zlib == false) {
		len = nmsg__nmsg__pack(c->nmsg, buf);
	} else {
		nmsg_res res;
		nmsg_zbuf_t zbuf;
		size_t ulen;
		u_char *zb_tmp;

		zb_tmp = malloc(c->estsz);
		if (zb_tmp == NULL) {
			free(*pbuf);
			return (nmsg_res_memfail);
		}

		zbuf = nmsg_zbuf_deflate_init();
		if (zbuf == NULL) {
			free(zb_tmp);
			free(*pbuf);
			return (nmsg_res_memfail);
		}

		ulen = nmsg__nmsg__pack(c->nmsg, zb_tmp);
		len = 2 * c->estsz;
		res = nmsg_zbuf_deflate(zbuf, ulen, zb_tmp, &len, buf);
		nmsg_zbuf_destroy(&zbuf);
		free(zb_tmp);
		if (res != nmsg_res_success)
			return (res);
	}

	if (do_header) {
		/* write the length of the container data */
		store_net32(len_wire, len);
		*buf_len = NMSG_HDRLSZ_V2 + len;
	} else {
		*buf_len = len;
	}
	
	_nmsg_dprintf(6, "%s: buf= %p len= %zd\n", __func__, buf, len);

	return (nmsg_res_success);
}