summaryrefslogtreecommitdiff
path: root/utils.c
blob: 0c763bc3fba053f526086056579302d5c14c9cb4 (plain)
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
87
88
89
90
91
92
93
94
95
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "utils.h"

#define MAX_UNIX_FDS	32

#define LOG(fmt, args ...) \
	fprintf(stderr, ">>> UDTRACE: " fmt, ## args)

/***********************************************************************
 * Utility functions
 ***********************************************************************/

static int unix_fds[MAX_UNIX_FDS];

__attribute__ ((constructor)) static void udtrace_init(void) {
	int i;
	LOG("Unix Domain Socket Trace initialized\n");
	for (i = 0; i < ARRAY_SIZE(unix_fds); i++) {
		unix_fds[i] = -1;
	}
}

/* add a file descriptor from the list of to-be-traced ones */
void add_fd(int fd)
{
	int i;
	for (i = 0; i < ARRAY_SIZE(unix_fds); i++) {
		if (unix_fds[i] == -1) {
			LOG("Adding FD %d\n", fd);
			unix_fds[i] = fd;
			return;
		}
	}
	LOG("Couldn't add UNIX FD %d (no space in unix_fds)\n", fd);
}

/* delete a file descriptor from the list of to-be-traced ones */
void del_fd(int fd)
{
	int i;
	for (i = 0; i < ARRAY_SIZE(unix_fds); i++) {
		if (unix_fds[i] == fd) {
			LOG("Removing FD %d\n", fd);
			unix_fds[i] = -1;
			return;
		}
	}
	LOG("Couldn't delete UNIX FD %d (no such FD)\n", fd);
}

/* is the given file descriptor part of the to-be-traced unix domain fd's? */
bool is_unix_socket(int fd)
{
	int i;
	for (i = 0; i < ARRAY_SIZE(unix_fds); i++) {
		if (unix_fds[i] == fd)
			return true;
	}
	return false;
}


/* taken from libosmocore */
static char hexd_buff[4096];
static const char hex_chars[] = "0123456789abcdef";
char *udtrace_hexdump(const unsigned char *buf, int len, char *delim)
{
	int i;
	char *cur = hexd_buff;

	hexd_buff[0] = 0;
	for (i = 0; i < len; i++) {
		const char *delimp = delim;
		int len_remain = sizeof(hexd_buff) - (cur - hexd_buff);
		if (len_remain < 3)
			break;

		*cur++ = hex_chars[buf[i] >> 4];
		*cur++ = hex_chars[buf[i] & 0xf];

		while (len_remain > 1 && *delimp) {
			*cur++ = *delimp++;
			len_remain--;
		}

		*cur = 0;
	}
	hexd_buff[sizeof(hexd_buff)-1] = 0;
	return hexd_buff;
}
personal git repositories of Harald Welte. Your mileage may vary