File: packets.c

package info (click to toggle)
lsfcc 0.2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 324 kB
  • ctags: 217
  • sloc: ansic: 1,551; yacc: 408; sh: 337; lex: 85; makefile: 55
file content (86 lines) | stat: -rw-r--r-- 1,705 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdlib.h>
#include <string.h>

#include "packets.h"

struct packet {
	char *id;
	struct field *fields;
	int numfields;
} *packets = NULL;
int numpackets = 0;

char *field_add(struct fields *f, char *id, int len) {
	int i;
	struct field *tf;

	for(i = 0; i < f->num; i++)
		if(!strcmp(f->f[i].id, id))
			return "Duplicate field %s defined, skipping";
	f->f = realloc(f->f, ++f->num * sizeof(*f->f));
	tf = f->f + f->num - 1;
	tf->id = strdup(id);
	tf->len = len;
	return NULL;
}
	
char *packet_add(char *id, struct fields *f) {
	int i;
	struct packet *tp;

	for(i = 0; i < numpackets; i++)
		if(!strcmp(packets[i].id, id)) {
			free(f->f);
			free(f);
			return "Redefinition of packet type %s ignored";
		}
	packets = realloc(packets, ++numpackets * sizeof(*packets));
	tp = packets + numpackets - 1;
	tp->id = strdup(id);
	tp->fields = f->f;
	tp->numfields = f->num;
	free(f);
	return NULL;
}

struct fields *fields_new() {
	struct fields *tmp;

	tmp = malloc(sizeof(*tmp));
	memset(tmp, 0, sizeof(*tmp));
	return tmp;
}

int packet_size(char *id) {
	int i;

	for(i = 0; i < numpackets; i++)
		if(!strcmp(packets[i].id, id)) {
			int size, j;
			
			size = 0;
			for(j = 0; j < packets[i].numfields; j++)
				size += packets[i].fields[j].len;
			return size;
		}
	return -1;
}

int packet_offset(char *pkt, char *field, int *offset, int *len) {
	int i;

	for(i = 0; i < numpackets; i++)
		if(!strcmp(packets[i].id, pkt)) {
			int size, j;
			
			size = 0;
			for(j = 0; j < packets[i].numfields; j++)
				if(!strcmp(packets[i].fields[j].id, field)) {
					*offset = size;
					*len = packets[i].fields[j].len;
					return 0;
				} else
					size += packets[i].fields[j].len;
		}
	return 1;
}