wm: dnsparser

ref: 13738d2aa200eeb5859525225ec1d7bec7e8134e
dir: /common.c/

View raw version
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

ulong pos;
ulong pktlen;

void
err(int fatal, char *fmt, ...)
{
	va_list args;
	va_start(args, fmt);
	
	fprintf(stderr, fatal ? "FATAL: " : "WARN: ");
	vfprintf(stderr, fmt, args);
	fprintf(stderr, "\n");
	
	va_end(args);

	if(fatal)
	{
		fflush(stdout);
		fclose(stdout);
		abort();
	}
}

uint16_t
get2(const u_char *octet)
{
	return octet[0] << 8 | octet[1];
}

uint32_t
get4(const u_char *octet)
{
	return get2(octet) << 8 * 2 | get2(octet + 2);
}

void*
emalloc(ulong len)
{
	void *m;
	
	m = malloc(len);
	
	if(m == NULL)
		err(1, "emalloc(%d): malloc failed, unable to allocate memory", len);
		
	return m;
}

void*
ecalloc(ulong len, ulong size)
{
	void *m;
	
	m = calloc(len, size);
	
	if(m == NULL)
		err(1, "ecalloc(%d, %d): calloc failed, unable to allocate memory", len, size);
		
	return m;
}

void*
memdup(const void *src, ulong len)
{
	void *dst;
	
	dst = emalloc(len);
	memmove(dst, src, len);
	
	return dst;
}

void
get(const u_char *pkt, long size, ...)
{
	uint8_t *u8;
	uint16_t *u16;
	uint32_t *u32;
	
	va_list args;
	va_start(args, size);
	
	switch(size)
	{
		case 1:
			u8 = va_arg(args, u_char*);
			*u8 = pkt[pos];
			break;
		case 2:
			u16 = va_arg(args, uint16_t*);
			*u16 = get2(pkt + pos);
			break;
		case 3:
			u32 = va_arg(args, uint32_t*);
			*u32 = get4(pkt + pos) >> 8;
			// *u32 &= 0x00ffffff;
			break;
		case 4:
			u32 = va_arg(args, uint32_t*);
			*u32 = get4(pkt + pos);
			break;
		default:
			err(1, "get(%p, %ld, ...): unsupported size", pkt, size);
	}
	pos += size;
	va_end(args);
}