From 0f361ed4d4e4ca48c35a5e59d57e2e1ecd60b07e Mon Sep 17 00:00:00 2001 From: Thomas Wade Date: Tue, 8 Oct 2019 14:42:29 +1030 Subject: [PATCH] Mass re-indent and reformat --- client/captureme.c | 624 ++++++++++++++++++------------------- server/svrcapture.c | 734 ++++++++++++++++++++++---------------------- 2 files changed, 679 insertions(+), 679 deletions(-) diff --git a/client/captureme.c b/client/captureme.c index bb2001c..e1fb4df 100755 --- a/client/captureme.c +++ b/client/captureme.c @@ -130,49 +130,49 @@ void dump_packet(char *msg, unsigned char *buffer, int n); struct serial_port { - int fd; - int rfd900_tx_count; - int rfd900_rx_count; + int fd; + int rfd900_tx_count; + int rfd900_rx_count; - char *port; - int id; + char *port; + int id; - // For !! tx mode, here is the accumulated transmitted packet - unsigned char tx_buff[1024]; - int tx_bytes; - int tx_state; + // For !! tx mode, here is the accumulated transmitted packet + unsigned char tx_buff[1024]; + int tx_bytes; + int tx_state; - // For RX mode, we look for the envelope our RFD900 firmware puts following a received packet - unsigned char rx_buff[1024]; - int rx_bytes; + // For RX mode, we look for the envelope our RFD900 firmware puts following a received packet + unsigned char rx_buff[1024]; + int rx_bytes; }; long long start_time = 0; long long gettime_ms() { - long long retVal = -1; + long long retVal = -1; - do - { - struct timeval nowtv; - - // If gettimeofday() fails or returns an invalid value, all else is lost! - if (gettimeofday(&nowtv, NULL) == -1) + do { - perror("gettimeofday returned -1"); - break; - } + struct timeval nowtv; - if (nowtv.tv_sec < 0 || nowtv.tv_usec < 0 || nowtv.tv_usec >= 1000000) - { - perror("gettimeofday returned invalid value"); - break; - } + // If gettimeofday() fails or returns an invalid value, all else is lost! + if (gettimeofday(&nowtv, NULL) == -1) + { + perror("gettimeofday returned -1"); + break; + } - retVal = nowtv.tv_sec * 1000LL + nowtv.tv_usec / 1000; - } while (0); + if (nowtv.tv_sec < 0 || nowtv.tv_usec < 0 || nowtv.tv_usec >= 1000000) + { + perror("gettimeofday returned invalid value"); + break; + } - return retVal; + retVal = nowtv.tv_sec * 1000LL + nowtv.tv_usec / 1000; + } while (0); + + return retVal; } #define MAX_PORTS 16 @@ -181,98 +181,98 @@ int serial_port_count = 0; int set_nonblock(int fd) { - int retVal = 0; - - do - { - if (fd == -1) - break; + int retVal = 0; - int flags; - if ((flags = fcntl(fd, F_GETFL, NULL)) == -1) - { - perror("fcntl"); - printf("set_nonblock: fcntl(%d,F_GETFL,NULL)", fd); - retVal = -1; - break; - } - if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) + do { - perror("fcntl"); - printf("set_nonblock: fcntl(%d,F_SETFL,n|O_NONBLOCK)", fd); - return -1; - } - } while (0); - return retVal; + if (fd == -1) + break; + + int flags; + if ((flags = fcntl(fd, F_GETFL, NULL)) == -1) + { + perror("fcntl"); + printf("set_nonblock: fcntl(%d,F_GETFL,NULL)", fd); + retVal = -1; + break; + } + if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) + { + perror("fcntl"); + printf("set_nonblock: fcntl(%d,F_SETFL,n|O_NONBLOCK)", fd); + return -1; + } + } while (0); + return retVal; } int serial_setup_port_with_speed(int fd, int speed) { - struct termios t; - - tcgetattr(fd, &t); - fprintf(stderr, "Serial port settings before tcsetaddr: c=%08x, i=%08x, o=%08x, l=%08x\n", - (unsigned int)t.c_cflag, (unsigned int)t.c_iflag, - (unsigned int)t.c_oflag, (unsigned int)t.c_lflag); - - speed_t baud_rate; - switch (speed) - { - case 115200: - baud_rate = B115200; - break; - case 230400: - baud_rate = B230400; - break; - } - - // XXX Speed and options should be configurable - if (cfsetospeed(&t, baud_rate)) - return -1; - if (cfsetispeed(&t, baud_rate)) - return -1; - - // 8N1 - t.c_cflag &= ~PARENB; - t.c_cflag &= ~CSTOPB; - t.c_cflag &= ~CSIZE; - t.c_cflag |= CS8; - t.c_cflag |= CLOCAL; - - t.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO | ECHOE); - //Noncanonical mode, disable signals, extended - //input processing, and software flow control and echoing - - t.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR | - INPCK | ISTRIP | IXON | IXOFF | IXANY | PARMRK); - //Disable special handling of CR, NL, and BREAK. - //No 8th-bit stripping or parity error handling. - //Disable START/STOP output flow control. - - // Disable CTS/RTS flow control + struct termios t; + + tcgetattr(fd, &t); + fprintf(stderr, "Serial port settings before tcsetaddr: c=%08x, i=%08x, o=%08x, l=%08x\n", + (unsigned int)t.c_cflag, (unsigned int)t.c_iflag, + (unsigned int)t.c_oflag, (unsigned int)t.c_lflag); + + speed_t baud_rate; + switch (speed) + { + case 115200: + baud_rate = B115200; + break; + case 230400: + baud_rate = B230400; + break; + } + + // XXX Speed and options should be configurable + if (cfsetospeed(&t, baud_rate)) + return -1; + if (cfsetispeed(&t, baud_rate)) + return -1; + + // 8N1 + t.c_cflag &= ~PARENB; + t.c_cflag &= ~CSTOPB; + t.c_cflag &= ~CSIZE; + t.c_cflag |= CS8; + t.c_cflag |= CLOCAL; + + t.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO | ECHOE); + //Noncanonical mode, disable signals, extended + //input processing, and software flow control and echoing + + t.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR | + INPCK | ISTRIP | IXON | IXOFF | IXANY | PARMRK); + //Disable special handling of CR, NL, and BREAK. + //No 8th-bit stripping or parity error handling. + //Disable START/STOP output flow control. + + // Disable CTS/RTS flow control #ifndef CNEW_RTSCTS - t.c_cflag &= ~CRTSCTS; + t.c_cflag &= ~CRTSCTS; #else - t.c_cflag &= ~CNEW_RTSCTS; + t.c_cflag &= ~CNEW_RTSCTS; #endif - // no output processing - t.c_oflag &= ~OPOST; + // no output processing + t.c_oflag &= ~OPOST; - fprintf(stderr, "Serial port settings attempting to be set: c=%08x, i=%08x, o=%08x, l=%08x\n", - (unsigned int)t.c_cflag, (unsigned int)t.c_iflag, - (unsigned int)t.c_oflag, (unsigned int)t.c_lflag); + fprintf(stderr, "Serial port settings attempting to be set: c=%08x, i=%08x, o=%08x, l=%08x\n", + (unsigned int)t.c_cflag, (unsigned int)t.c_iflag, + (unsigned int)t.c_oflag, (unsigned int)t.c_lflag); - tcsetattr(fd, TCSANOW, &t); + tcsetattr(fd, TCSANOW, &t); - tcgetattr(fd, &t); - fprintf(stderr, "Serial port settings after tcsetaddr: c=%08x, i=%08x, o=%08x, l=%08x\n", - (unsigned int)t.c_cflag, (unsigned int)t.c_iflag, - (unsigned int)t.c_oflag, (unsigned int)t.c_lflag); + tcgetattr(fd, &t); + fprintf(stderr, "Serial port settings after tcsetaddr: c=%08x, i=%08x, o=%08x, l=%08x\n", + (unsigned int)t.c_cflag, (unsigned int)t.c_iflag, + (unsigned int)t.c_oflag, (unsigned int)t.c_lflag); - set_nonblock(fd); + set_nonblock(fd); - return 0; + return 0; } int record_rfd900_event(struct serial_port *sp, unsigned char *packet, int len, char* type) @@ -317,46 +317,46 @@ int record_rfd900_event(struct serial_port *sp, unsigned char *packet, int len, int setup_monitor_port(char *path, int speed) { - int retVal = 0; + int retVal = 0; - do - { - if (serial_port_count >= MAX_PORTS) + do { - fprintf(stderr, "Too many serial ports. (Increase MAX_PORTS?)\n"); - retVal = -3; - break; - } + if (serial_port_count >= MAX_PORTS) + { + fprintf(stderr, "Too many serial ports. (Increase MAX_PORTS?)\n"); + retVal = -3; + break; + } - //open serial port - int r1 = open(path, O_RDONLY | O_NOCTTY | O_NDELAY); - if (r1 == -1) - { - fprintf(stderr, "Failed to open serial port '%s'\n", path); - retVal = -3; - break; - } + //open serial port + int r1 = open(path, O_RDONLY | O_NOCTTY | O_NDELAY); + if (r1 == -1) + { + fprintf(stderr, "Failed to open serial port '%s'\n", path); + retVal = -3; + break; + } - serial_ports[serial_port_count].fd = r1; - serial_ports[serial_port_count].port = strdup(path); - serial_ports[serial_port_count].id = serial_port_count; - serial_ports[serial_port_count].rfd900_tx_count = 0; - serial_ports[serial_port_count].rfd900_rx_count = 0; - serial_ports[serial_port_count].tx_state = 0; - serial_ports[serial_port_count].tx_bytes = 0; + serial_ports[serial_port_count].fd = r1; + serial_ports[serial_port_count].port = strdup(path); + serial_ports[serial_port_count].id = serial_port_count; + serial_ports[serial_port_count].rfd900_tx_count = 0; + serial_ports[serial_port_count].rfd900_rx_count = 0; + serial_ports[serial_port_count].tx_state = 0; + serial_ports[serial_port_count].tx_bytes = 0; - //set non blocking for the serial ports for continous loop - set_nonblock(r1); + //set non blocking for the serial ports for continous loop + set_nonblock(r1); - //set serial port speeds - serial_setup_port_with_speed(r1, speed); + //set serial port speeds + serial_setup_port_with_speed(r1, speed); - printf("Initialised '%s' as serial port %d\n", path, serial_port_count); + printf("Initialised '%s' as serial port %d\n", path, serial_port_count); - serial_port_count++; + serial_port_count++; - } while (0); - return retVal; + } while (0); + return retVal; } int process_serial_char(struct serial_port *sp, unsigned char c) @@ -437,24 +437,24 @@ int process_serial_char(struct serial_port *sp, unsigned char c) int process_serial_port(struct serial_port *sp) { - int i; - int retVal = 0; - int bytes_read; - unsigned char buffer[128]; // small buffer, so we round-robin among the ports more often - do - { - bytes_read = read(sp->fd, buffer, sizeof(buffer)); - - if (bytes_read > 0) + int i; + int retVal = 0; + int bytes_read; + unsigned char buffer[128]; // small buffer, so we round-robin among the ports more often + do { - dump_packet("read", buffer, bytes_read); - printf("Read Size: %i\n", bytes_read); - for (i = 0; i < bytes_read; i++) - process_serial_char(sp, buffer[i]); - } - } while (0); + bytes_read = read(sp->fd, buffer, sizeof(buffer)); - return retVal; + if (bytes_read > 0) + { + dump_packet("read", buffer, bytes_read); + printf("Read Size: %i\n", bytes_read); + for (i = 0; i < bytes_read; i++) + process_serial_char(sp, buffer[i]); + } + } while (0); + + return retVal; } void dump_packet(char *msg, unsigned char *buffer, int n) @@ -490,7 +490,7 @@ void dump_packet(char *msg, unsigned char *buffer, int n) int main(int argc, char **argv) { - int retVal = 0; + int retVal = 0; // Define args struct and populate simple defaults arguments args; @@ -503,56 +503,56 @@ int main(int argc, char **argv) // Parse command line args argp_parse(&argp_parser, argc, argv, 0, 0, &args); - do - { - printf("Before variable declaration\n"); - int sockfd; - FILE *outFile = fopen(PCAP_FILE, "ab"); // append to file only + do + { + printf("Before variable declaration\n"); + int sockfd; + FILE *outFile = fopen(PCAP_FILE, "ab"); // append to file only #ifdef TEST - int serverlen; + int serverlen; #endif - //setup wireless capture settings - char *dev = args.wifidev; - char errbuf[PCAP_ERRBUF_SIZE]; - struct bpf_program fp; // hold compiled libpcap filter program - pcap_t *handle; - struct pcap_pkthdr header; - int timeout = 10, n; - bpf_u_int32 maskp; // subnet mask - bpf_u_int32 ip; // ip - - printf("My Mesh Extender ID is: %s\n", myMeshExtenderID); - - printf("Before packet injection setup\n"); - //setup packet injection - source used: https://www.cs.cmu.edu/afs/cs/academic/class/15213-f99/www/class26/udpclient.c - u_char *capPacket; - bzero((char *)&serv_addr, sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr = args.address; - int portno = args.port; - serv_addr.sin_port = htons(portno); - char hbuf[NI_MAXHOST]; - socklen_t len = sizeof(struct sockaddr_in); - - //setup sockets - printf("Before socket setup\n"); - sockfd = socket(AF_INET, SOCK_DGRAM, 0); - if (sockfd < 0) - { - perror("Error setting up socket\n"); - retVal = -2; - return (retVal); - } - else - { - printf("Will send data to %s:%i\n", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port)); - } + //setup wireless capture settings + char *dev = args.wifidev; + char errbuf[PCAP_ERRBUF_SIZE]; + struct bpf_program fp; // hold compiled libpcap filter program + pcap_t *handle; + struct pcap_pkthdr header; + int timeout = 10, n; + bpf_u_int32 maskp; // subnet mask + bpf_u_int32 ip; // ip + + printf("My Mesh Extender ID is: %s\n", myMeshExtenderID); + + printf("Before packet injection setup\n"); + //setup packet injection - source used: https://www.cs.cmu.edu/afs/cs/academic/class/15213-f99/www/class26/udpclient.c + u_char *capPacket; + bzero((char *)&serv_addr, sizeof(serv_addr)); + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr = args.address; + int portno = args.port; + serv_addr.sin_port = htons(portno); + char hbuf[NI_MAXHOST]; + socklen_t len = sizeof(struct sockaddr_in); + + //setup sockets + printf("Before socket setup\n"); + sockfd = socket(AF_INET, SOCK_DGRAM, 0); + if (sockfd < 0) + { + perror("Error setting up socket\n"); + retVal = -2; + return (retVal); + } + else + { + printf("Will send data to %s:%i\n", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port)); + } - serversock = sockfd; + serversock = sockfd; #ifdef TEST - if (getnameinfo((struct sockaddr *)&serv_addr, len, hbuf, sizeof(hbuf), NULL, 0, 0)) + if (getnameinfo((struct sockaddr *)&serv_addr, len, hbuf, sizeof(hbuf), NULL, 0, 0)) { printf("could not resolve IP\n"); retVal = -1; @@ -564,150 +564,150 @@ int main(int argc, char **argv) } #endif - if (args.uhfCapture) - { - printf("Before serial port setup\n"); - - //setup serial ports - // Start with all on same speed, so that we can - // figure out the pairs of ports that are connected - // to the same wire - setup_monitor_port("/dev/ttyUSB0", 230400); - setup_monitor_port("/dev/ttyUSB1", 230400); - setup_monitor_port("/dev/ttyUSB2", 230400); - setup_monitor_port("/dev/ttyUSB3", 230400); - - // Then wait for input on one, and see if the same character - // appears on another very soon there after. - // (This assumes that there is traffic on at least one - // of the ports. If not, then there is nothing to collect, anyway. - int links_setup = 0; - while (links_setup == 0) + if (args.uhfCapture) { - char buff[1024]; - int i = 0; - for (; i < 4; i++) + printf("Before serial port setup\n"); + + //setup serial ports + // Start with all on same speed, so that we can + // figure out the pairs of ports that are connected + // to the same wire + setup_monitor_port("/dev/ttyUSB0", 230400); + setup_monitor_port("/dev/ttyUSB1", 230400); + setup_monitor_port("/dev/ttyUSB2", 230400); + setup_monitor_port("/dev/ttyUSB3", 230400); + + // Then wait for input on one, and see if the same character + // appears on another very soon there after. + // (This assumes that there is traffic on at least one + // of the ports. If not, then there is nothing to collect, anyway. + int links_setup = 0; + while (links_setup == 0) { - int n = read(serial_ports[i].fd, buff, 1024); - if (n > 0) + char buff[1024]; + int i = 0; + for (; i < 4; i++) { - // We have some input, so now look for it on the other ports. - // But give the USB serial adapters time to catch up, as they frequently - // have 16ms of latency. We allow 50ms here to be safe. - usleep(50000); - char buff2[1024]; - int j = 0; - for (; j < 4; j++) + int n = read(serial_ports[i].fd, buff, 1024); + if (n > 0) { - // Don't look for the data on ourselves - if (i == j) - continue; - int n2 = read(serial_ports[j].fd, buff2, 1024); - if (n2 >= n) + // We have some input, so now look for it on the other ports. + // But give the USB serial adapters time to catch up, as they frequently + // have 16ms of latency. We allow 50ms here to be safe. + usleep(50000); + char buff2[1024]; + int j = 0; + for (; j < 4; j++) { - if (!bcmp(buff, buff2, n)) + // Don't look for the data on ourselves + if (i == j) + continue; + int n2 = read(serial_ports[j].fd, buff2, 1024); + if (n2 >= n) { - printf("Serial ports %d and %d seem to be linked.\n", i, j); - - // Set one of those to 115200, and then one of the other two ports to 115200, - // and then we should have both speeds on both ports available - serial_setup_port_with_speed(serial_ports[i].fd, 115200); - int k = 0; - for (; k < 4; k++) + if (!bcmp(buff, buff2, n)) { - if (k == i) - continue; - if (k == j) - continue; - serial_setup_port_with_speed(serial_ports[k].fd, 115200); - links_setup = 1; - break; + printf("Serial ports %d and %d seem to be linked.\n", i, j); + + // Set one of those to 115200, and then one of the other two ports to 115200, + // and then we should have both speeds on both ports available + serial_setup_port_with_speed(serial_ports[i].fd, 115200); + int k = 0; + for (; k < 4; k++) + { + if (k == i) + continue; + if (k == j) + continue; + serial_setup_port_with_speed(serial_ports[k].fd, 115200); + links_setup = 1; + break; + } } } } } } + // Wait a little while before trying again + usleep(50000); } - // Wait a little while before trying again - usleep(50000); } - } - if (args.wifiCapture) - { - printf("Before pcap setup\n"); + if (args.wifiCapture) + { + printf("Before pcap setup\n"); - pcap_lookupnet(dev, &ip, &maskp, errbuf); + pcap_lookupnet(dev, &ip, &maskp, errbuf); - //open handle for wireless device - handle = pcap_open_live(dev, BUFSIZ, 1, timeout, errbuf); - if (handle == NULL) - { - printf("Error starting pcap device: %s\n", errbuf); - } + //open handle for wireless device + handle = pcap_open_live(dev, BUFSIZ, 1, timeout, errbuf); + if (handle == NULL) + { + printf("Error starting pcap device: %s\n", errbuf); + } - // Set non-blocking mode - if (pcap_setnonblock(handle, 1, errbuf)) - { - printf("Error setting pcap device to non-blocking: %s\n", errbuf); - } + // Set non-blocking mode + if (pcap_setnonblock(handle, 1, errbuf)) + { + printf("Error setting pcap device to non-blocking: %s\n", errbuf); + } - if (pcap_compile(handle, &fp, args.filter, 0, ip) == -1) - { - printf("Bad filter - %s\n", pcap_geterr(handle)); - printf("For more information on pcap filters, see 'man pcap-filter' or https://www.tcpdump.org/manpages/pcap-filter.7.html\n"); - retVal = -8; - break; - } + if (pcap_compile(handle, &fp, args.filter, 0, ip) == -1) + { + printf("Bad filter - %s\n", pcap_geterr(handle)); + printf("For more information on pcap filters, see 'man pcap-filter' or https://www.tcpdump.org/manpages/pcap-filter.7.html\n"); + retVal = -8; + break; + } - if (pcap_setfilter(handle, &fp) == -1) - { - fprintf(stderr, "Error setting filter\n"); - retVal = -8; - break; + if (pcap_setfilter(handle, &fp) == -1) + { + fprintf(stderr, "Error setting filter\n"); + retVal = -8; + break; + } } - } - // While loop that serially searches for a packet to be captured by all devices (round robin) - printf("Before loop\n"); - do - { - if (args.uhfCapture) + // While loop that serially searches for a packet to be captured by all devices (round robin) + printf("Before loop\n"); + do { - int i; - for (i = 0; i < serial_port_count; i++) + if (args.uhfCapture) { - process_serial_port(&serial_ports[i]); + int i; + for (i = 0; i < serial_port_count; i++) + { + process_serial_port(&serial_ports[i]); + } } - } - if (args.wifiCapture) - { - header.len = 0; - header.caplen = 0; - capPacket = pcap_next(handle, &header); - if (capPacket && header.len > 0) + if (args.wifiCapture) { - printf("Captured WIFI packet total length %i\n", header.len); - n = sendto(sockfd, capPacket, header.len, 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); - //dump_packet("Captured Packet", capPacket, n); - printf("Size Written %i\n", n); - if (n < 0) + header.len = 0; + header.caplen = 0; + capPacket = pcap_next(handle, &header); + if (capPacket && header.len > 0) { - perror("Error Sending\n"); - retVal = -11; - perror("Sendto: "); - break; + printf("Captured WIFI packet total length %i\n", header.len); + n = sendto(sockfd, capPacket, header.len, 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); + //dump_packet("Captured Packet", capPacket, n); + printf("Size Written %i\n", n); + if (n < 0) + { + perror("Error Sending\n"); + retVal = -11; + perror("Sendto: "); + break; + } } } - } - } while (1); + } while (1); - printf("Closing output file.\n"); - //close opened file - fclose(outFile); + printf("Closing output file.\n"); + //close opened file + fclose(outFile); - } while (0); + } while (0); - return (retVal); + return (retVal); } diff --git a/server/svrcapture.c b/server/svrcapture.c index 9118432..81cd911 100755 --- a/server/svrcapture.c +++ b/server/svrcapture.c @@ -1,6 +1,6 @@ /* A simple server in the internet domain using TCP - The port number is passed as an argument - This version runs forever, forking off a separate + The port number is passed as an argument + This version runs forever, forking off a separate process for each connection gcc server2.c -lsocket */ @@ -106,58 +106,58 @@ static struct argp argp_parser = {options, parse_arg, argument_doc, 0}; volatile sig_atomic_t sigint_flag = 0; void sigint_handler(int signal) { - sigint_flag = 1; + sigint_flag = 1; } long long start_time = 0; long long gettime_ms() { - long long retVal = -1; + long long retVal = -1; - do - { - struct timeval nowtv; + do + { + struct timeval nowtv; - // If gettimeofday() fails or returns an invalid value, all else is lost! - if (gettimeofday(&nowtv, NULL) == -1) - { - perror("gettimeofday returned -1"); - break; - } + // If gettimeofday() fails or returns an invalid value, all else is lost! + if (gettimeofday(&nowtv, NULL) == -1) + { + perror("gettimeofday returned -1"); + break; + } - if (nowtv.tv_sec < 0 || nowtv.tv_usec < 0 || nowtv.tv_usec >= 1000000) - { - perror("gettimeofday returned invalid value"); - break; - } + if (nowtv.tv_sec < 0 || nowtv.tv_usec < 0 || nowtv.tv_usec >= 1000000) + { + perror("gettimeofday returned invalid value"); + break; + } - retVal = nowtv.tv_sec * 1000LL + nowtv.tv_usec / 1000; - } while (0); + retVal = nowtv.tv_sec * 1000LL + nowtv.tv_usec / 1000; + } while (0); - return retVal; + return retVal; } void dump_packet(char *msg, unsigned char *b, int n) { - printf("%s: Displaying %d bytes.\n", msg, n); - for (int i = 0; i < n; i += 16) - { - int j; - printf("%08X : ", i); - for (j = 0; j < 16 && (i + j) < n; j++) - printf("%02X ", b[i + j]); - for (; j < 16; j++) - printf(" "); - for (j = 0; j < 16 && (i + j) < n; j++) - if (b[i + j] >= ' ' && b[i + j] < 0x7f) - { - printf("%c", b[i + j]); - } - else - printf("."); - printf("\n"); - } + printf("%s: Displaying %d bytes.\n", msg, n); + for (int i = 0; i < n; i += 16) + { + int j; + printf("%08X : ", i); + for (j = 0; j < 16 && (i + j) < n; j++) + printf("%02X ", b[i + j]); + for (; j < 16; j++) + printf(" "); + for (j = 0; j < 16 && (i + j) < n; j++) + if (b[i + j] >= ' ' && b[i + j] < 0x7f) + { + printf("%c", b[i + j]); + } + else + printf("."); + printf("\n"); + } } int parse_mac(unsigned char* mac, char* buffer) @@ -168,28 +168,28 @@ int parse_mac(unsigned char* mac, char* buffer) void decode_wifi(unsigned char *packet, int len, FILE* output_file) { - printf("\n\n WIFI PACKET \n"); + printf("\n\n WIFI PACKET \n"); // Dump the contents to the terminal dump_packet("Packet contents", packet, len); - // Parse the packet headers + // Parse the packet headers parsed_packet headers = parse_packet(packet, len); - // Parse the MAC addresses as neatly-formatted C strings - char parsedSrcMac[18]; + // Parse the MAC addresses as neatly-formatted C strings + char parsedSrcMac[18]; char parsedDstMac[18]; parse_mac(headers.header_80211.source, parsedSrcMac); parse_mac(headers.header_80211.dest, parsedDstMac); // Print out the source and destination - printf("src MAC: %s\n", parsedSrcMac); - printf("dst MAC: %s\n", parsedDstMac); + printf("src MAC: %s\n", parsedSrcMac); + printf("dst MAC: %s\n", parsedDstMac); - // Parse the header on the highest level of the OSI stack - char protocol[16]; - char message[64]; - switch (headers.highest_header) + // Parse the header on the highest level of the OSI stack + char protocol[16]; + char message[64]; + switch (headers.highest_header) { case Rhizome: printf("This is a Rhizome packet\n"); @@ -270,212 +270,212 @@ void decode_wifi(unsigned char *packet, int len, FILE* output_file) break; } - // Write to the diagram - fprintf(output_file, "\"%s\" -> \"%s\": T+%lldms - %s: %s\n", parsedSrcMac, parsedDstMac, gettime_ms() - start_time, protocol, message); + // Write to the diagram + fprintf(output_file, "\"%s\" -> \"%s\": T+%lldms - %s: %s\n", parsedSrcMac, parsedDstMac, gettime_ms() - start_time, protocol, message); } int decode_lbard(unsigned char *msg, int len, FILE *output_file, char *myAttachedMeshExtender) { - int areWeSending=1; //use this to see if we are sending or recieving - int iterationTest = 1; - int offset = 8; - int peer_index = -1; - while (offset < len) - { - /* - Parse message and act on it. + int areWeSending=1; //use this to see if we are sending or recieving + int iterationTest = 1; + int offset = 8; + int peer_index = -1; + while (offset < len) + { + /* + Parse message and act on it. */ - // All valid messages must be at least 8 bytes long. - if (len < 8) - return -1; - char peer_prefix[6 * 2 + 1]; - snprintf(peer_prefix, 6 * 2 + 1, "%02x%02x%02x%02x%02x%02x", - msg[0], msg[1], msg[2], msg[3], msg[4], msg[5]); - int msg_number = msg[6] + 256 * (msg[7] & 0x7f); - int is_retransmission = msg[7] & 0x80; - - // Find or create peer structure for this. - struct peer_state *p = NULL; - for (int i = 0; i < peer_count; i++) - { - if (!strcasecmp(peer_records[i]->sid_prefix, peer_prefix)) - { - p = peer_records[i]; - peer_index = i; - break; - } - } - - - if (!p) - { - p = calloc(1, sizeof(struct peer_state)); - for (int i = 0; i < 4; i++) - p->sid_prefix_bin[i] = msg[i]; - p->sid_prefix = strdup(peer_prefix); - p->last_message_number = -1; - p->tx_bundle = -1; - p->request_bitmap_bundle = -1; - } - - // Update time stamp and most recent message from peer - if (msg_number > p->last_message_number) - { - // We probably have missed packets. - // But only count if gap is <256, since more than that probably means - // something more profound has happened. - p->missed_packet_count += msg_number - p->last_message_number - 1; - } - p->last_message_time = time(0); - - if (!is_retransmission) - p->last_message_number = msg_number; - int advance; - while (offset < len) - { - printf("Offset: %i, len %i\n", offset, len); - dump_packet("Packet offset", msg, len); - - iterationTest ++; - printf("Message Type: %c - 0x%02X\n", msg[offset], msg[offset]); - - if (message_handlers[msg[offset]]) - { - char message_description[8192]; - printf("Calling message handler for type 0x%02x @ offset 0x%x\n", - msg[offset], offset); - advance = message_handlers[msg[offset]](p, peer_prefix, NULL, NULL, - &msg[offset], len - offset, message_description); - printf("Message description: %s\n", message_description); - - long long relative_time_ms; - relative_time_ms = gettime_ms() - start_time; - - if (strncasecmp(msg, "LBARD:RFD900:TX:", 16)) - { - fprintf(output_file, "%s -> BROADCAST: T+%lldms %c - %s\n", peer_prefix, - relative_time_ms, msg[offset], message_description); - } else - { - fprintf(output_file, "BROADCAST -> %s: T+%lldms %c - %s\n", peer_prefix, - relative_time_ms, msg[offset], message_description); - } - - - if (advance < 1) - { - fprintf(stderr, - "At packet offset 0x%x, message parser 0x%02x returned zero or negative message length (=%d).\n" - " Assuming packet is corrupt.\n", - offset, msg[offset], advance); - return -1; - } - printf("### %s : Handler consumed %d packet bytes.\n", timestamp_str(), advance); - offset += advance; - } - else - { - // No parser for this message type - // invalid message field. - - char sender_prefix[128]; - char monitor_log_buf[1024]; - sprintf(sender_prefix, "%s*", p->sid_prefix); - - /*snprintf(monitor_log_buf, sizeof(monitor_log_buf), - "Illegal message field 0x%02X at radio packet offset %d", - msg[offset], offset); - fprintf(stderr, "Illegal message type 0x%02x at offset %d\n", msg[offset], offset);*/ - - return -1; - } - } - } - return 0; + // All valid messages must be at least 8 bytes long. + if (len < 8) + return -1; + char peer_prefix[6 * 2 + 1]; + snprintf(peer_prefix, 6 * 2 + 1, "%02x%02x%02x%02x%02x%02x", + msg[0], msg[1], msg[2], msg[3], msg[4], msg[5]); + int msg_number = msg[6] + 256 * (msg[7] & 0x7f); + int is_retransmission = msg[7] & 0x80; + + // Find or create peer structure for this. + struct peer_state *p = NULL; + for (int i = 0; i < peer_count; i++) + { + if (!strcasecmp(peer_records[i]->sid_prefix, peer_prefix)) + { + p = peer_records[i]; + peer_index = i; + break; + } + } + + + if (!p) + { + p = calloc(1, sizeof(struct peer_state)); + for (int i = 0; i < 4; i++) + p->sid_prefix_bin[i] = msg[i]; + p->sid_prefix = strdup(peer_prefix); + p->last_message_number = -1; + p->tx_bundle = -1; + p->request_bitmap_bundle = -1; + } + + // Update time stamp and most recent message from peer + if (msg_number > p->last_message_number) + { + // We probably have missed packets. + // But only count if gap is <256, since more than that probably means + // something more profound has happened. + p->missed_packet_count += msg_number - p->last_message_number - 1; + } + p->last_message_time = time(0); + + if (!is_retransmission) + p->last_message_number = msg_number; + int advance; + while (offset < len) + { + printf("Offset: %i, len %i\n", offset, len); + dump_packet("Packet offset", msg, len); + + iterationTest ++; + printf("Message Type: %c - 0x%02X\n", msg[offset], msg[offset]); + + if (message_handlers[msg[offset]]) + { + char message_description[8192]; + printf("Calling message handler for type 0x%02x @ offset 0x%x\n", + msg[offset], offset); + advance = message_handlers[msg[offset]](p, peer_prefix, NULL, NULL, + &msg[offset], len - offset, message_description); + printf("Message description: %s\n", message_description); + + long long relative_time_ms; + relative_time_ms = gettime_ms() - start_time; + + if (strncasecmp(msg, "LBARD:RFD900:TX:", 16)) + { + fprintf(output_file, "%s -> BROADCAST: T+%lldms %c - %s\n", peer_prefix, + relative_time_ms, msg[offset], message_description); + } else + { + fprintf(output_file, "BROADCAST -> %s: T+%lldms %c - %s\n", peer_prefix, + relative_time_ms, msg[offset], message_description); + } + + + if (advance < 1) + { + fprintf(stderr, + "At packet offset 0x%x, message parser 0x%02x returned zero or negative message length (=%d).\n" + " Assuming packet is corrupt.\n", + offset, msg[offset], advance); + return -1; + } + printf("### %s : Handler consumed %d packet bytes.\n", timestamp_str(), advance); + offset += advance; + } + else + { + // No parser for this message type + // invalid message field. + + char sender_prefix[128]; + char monitor_log_buf[1024]; + sprintf(sender_prefix, "%s*", p->sid_prefix); + + /*snprintf(monitor_log_buf, sizeof(monitor_log_buf), + "Illegal message field 0x%02X at radio packet offset %d", + msg[offset], offset); + fprintf(stderr, "Illegal message type 0x%02x at offset %d\n", msg[offset], offset);*/ + + return -1; + } + } + } + return 0; } int main(int argc, char *argv[]) { - // Register signal handlers - signal(SIGINT, sigint_handler); - - int retVal; - //int fd = fileno(stdin); - - // Define args struct and populate simple defaults - arguments args; - args.port = DEFAULT_PORT; - args.packets = DEFAULT_PACKET_CAPTURE_NUM; - args.jarpath = DEFAULT_PLANTUML_JAR_PATH; - - // Populate complex defaults - if (DEFAULT_ADDRESS == NULL) - { - args.address.s_addr = DEFAULT_ADDRESS; - } - else if (!inet_aton(DEFAULT_ADDRESS, &args.address)) - { - perror("Failed to parse and set default address"); - exit(1); - }; - - // Parse command line args - argp_parse(&argp_parser, argc, argv, 0, 0, &args); - - do - { - //get time to write to file name - time_t rawTime; - int bufferSize = 100; - struct tm *timeInfo; - time(&rawTime); - timeInfo = localtime(&rawTime); - char timingDiagramFileName[bufferSize]; - char *time = asctime(timeInfo); - time[strlen(time) - 1] = 0; //remove the new line at end of time - snprintf(timingDiagramFileName, bufferSize, "timingDiagram_%s.txt", time); - char myAttachedMeshExtender = argv[1]; - - FILE *outFile; - outFile = fopen(timingDiagramFileName, "w"); //open file to write to - fprintf(outFile, "@startuml\n"); //write first line of uml file - - //init socket variables - int sockfd, portno = args.port; - - sockfd = socket(AF_INET, SOCK_DGRAM, 0); - if (sockfd < 0) - { - perror("ERROR opening socket"); - exit(-1); - } - - //build server's internet address - struct sockaddr_in serv_addr, client_addr; - memset(&serv_addr, 0, sizeof(serv_addr)); //clear struct before setting up - memset(&client_addr, 0, sizeof(client_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr = args.address; //any source address - serv_addr.sin_port = htons(args.port); - - //bind sockets - if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) - { - perror("ERROR on binding"); - exit(-1); - } - - printf("Listening at %s:%i\n", inet_ntoa(serv_addr.sin_addr), args.port); - - //make variables for reading in packets - u_char packet[8192]; - - //main while loop to accept packet - //set starting time - start_time = gettime_ms(); - - // Print out a helpful reminder that this will run until you tell it to stop + // Register signal handlers + signal(SIGINT, sigint_handler); + + int retVal; + //int fd = fileno(stdin); + + // Define args struct and populate simple defaults + arguments args; + args.port = DEFAULT_PORT; + args.packets = DEFAULT_PACKET_CAPTURE_NUM; + args.jarpath = DEFAULT_PLANTUML_JAR_PATH; + + // Populate complex defaults + if (DEFAULT_ADDRESS == NULL) + { + args.address.s_addr = DEFAULT_ADDRESS; + } + else if (!inet_aton(DEFAULT_ADDRESS, &args.address)) + { + perror("Failed to parse and set default address"); + exit(1); + }; + + // Parse command line args + argp_parse(&argp_parser, argc, argv, 0, 0, &args); + + do + { + //get time to write to file name + time_t rawTime; + int bufferSize = 100; + struct tm *timeInfo; + time(&rawTime); + timeInfo = localtime(&rawTime); + char timingDiagramFileName[bufferSize]; + char *time = asctime(timeInfo); + time[strlen(time) - 1] = 0; //remove the new line at end of time + snprintf(timingDiagramFileName, bufferSize, "timingDiagram_%s.txt", time); + char myAttachedMeshExtender = argv[1]; + + FILE *outFile; + outFile = fopen(timingDiagramFileName, "w"); //open file to write to + fprintf(outFile, "@startuml\n"); //write first line of uml file + + //init socket variables + int sockfd, portno = args.port; + + sockfd = socket(AF_INET, SOCK_DGRAM, 0); + if (sockfd < 0) + { + perror("ERROR opening socket"); + exit(-1); + } + + //build server's internet address + struct sockaddr_in serv_addr, client_addr; + memset(&serv_addr, 0, sizeof(serv_addr)); //clear struct before setting up + memset(&client_addr, 0, sizeof(client_addr)); + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr = args.address; //any source address + serv_addr.sin_port = htons(args.port); + + //bind sockets + if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) + { + perror("ERROR on binding"); + exit(-1); + } + + printf("Listening at %s:%i\n", inet_ntoa(serv_addr.sin_addr), args.port); + + //make variables for reading in packets + u_char packet[8192]; + + //main while loop to accept packet + //set starting time + start_time = gettime_ms(); + + // Print out a helpful reminder that this will run until you tell it to stop if (args.packets > 0) { printf("Will capture %d packet%c\n", args.packets, args.packets > 1 ? 's' : '\0'); @@ -484,126 +484,126 @@ int main(int argc, char *argv[]) { printf("Will capture forever until stopped\n"); } - printf("Press Ctrl+C to stop capturing\n"); - fflush(stdout); - - // Accept and process incoming packets, will iterate until desired number of packets reached or stopped manually - for (int i = 0; args.packets > 0 ? i < args.packets && !sigint_flag : !sigint_flag; i++) - { - int bytesReceived = 0; - unsigned int addressLength; - - // Accept incoming message - while (!bytesReceived && !sigint_flag) - { - // Null-terminate the packet buffer - packet[0] = 0; - - // Receive packets (non-blocking) - bytesReceived = recvfrom( - sockfd, // Socket - packet, // Packet buffer - 8192, // Packet length - MSG_DONTWAIT, // Don't block and wait - (struct sockaddr *) &client_addr, // Source address - &addressLength // Address length - ); - - // Check if we haven't received anything - if (!bytesReceived) - { - usleep(100000); // Sleep for 100ms before we try again - printf("."); - fflush(stdout); - } - - // Handle errors - switch (errno) - { - case 0: // No error - break; - case EAGAIN: // Receive timed out - bytesReceived = 0; - break; - default: - perror("Unhandled error from recvfrom()"); - break; - } - - // Reset errno - errno = 0; - } - - // Kill the packet loop if we broke out with a SIGINT - if (sigint_flag) break; - - printf("Received %d bytes\n", bytesReceived); - - // Check for receive errors and break - if (bytesReceived < 0) - { - perror("ERROR in recieving packet\n"); - retVal = 1; - break; - } - - // Is this an LBARD packet? - if (packet[0] == 'L' && - packet[1] == 'B' && - packet[2] == 'A' && - packet[3] == 'R' && - packet[4] == 'D') - { - // Check if the packet is not just a header - if (sizeof(packet) > 5) - { - printf("About to call decode_lbard()\n"); - - // Initialise a buffer to store our decoded LBARD packet in - char lbardResult[8192]; - - // Decode the LABRD packet - // 16 byte offset before analysis to remove packet header - // 32 bytes of Reed-Solomon error correction trimmed from the end - // 1 byte of new line character that is an artifact of data collection removed from the end also - decode_lbard(&packet[16], bytesReceived - 16 - 32 - 1, outFile, myAttachedMeshExtender); - - // Null-terminate the decoded packet buffer - lbardResult[0] = '\0'; - } - } - else // Not an LBARD packet, must be from WiFi - { - // Decode wifi packet and put returned string into NTD text file - decode_wifi(&packet, bytesReceived, outFile); - } - - // Null-terminate the packet buffer - packet[0] = '\0'; - } - - //add final line to file - fprintf(outFile, "@enduml"); - - //run the program to create the graph - //change the arguments to where file location is ect - char *location = args.jarpath; - //get current working directory as this is where the generated textural file will be saved - char cwd[PATH_MAX]; - char command[256]; - getcwd(cwd, sizeof(cwd)); - - //wait to finish writing file - printf("writing diagram text file\n"); - fclose(outFile); - - //call program to make graph - printf("Making diagram in: %s\n", cwd); - snprintf(command, 256, "java -jar \'%s\' \'%s/%s\'", location, cwd, timingDiagramFileName); - //printf("Running following command to make graph\n %s\nPlease wait - Program will finish when diagram is made\n\n", command); - system(command); - - } while (0); - - return retVal; + printf("Press Ctrl+C to stop capturing\n"); + fflush(stdout); + + // Accept and process incoming packets, will iterate until desired number of packets reached or stopped manually + for (int i = 0; args.packets > 0 ? i < args.packets && !sigint_flag : !sigint_flag; i++) + { + int bytesReceived = 0; + unsigned int addressLength; + + // Accept incoming message + while (!bytesReceived && !sigint_flag) + { + // Null-terminate the packet buffer + packet[0] = 0; + + // Receive packets (non-blocking) + bytesReceived = recvfrom( + sockfd, // Socket + packet, // Packet buffer + 8192, // Packet length + MSG_DONTWAIT, // Don't block and wait + (struct sockaddr *) &client_addr, // Source address + &addressLength // Address length + ); + + // Check if we haven't received anything + if (!bytesReceived) + { + usleep(100000); // Sleep for 100ms before we try again + printf("."); + fflush(stdout); + } + + // Handle errors + switch (errno) + { + case 0: // No error + break; + case EAGAIN: // Receive timed out + bytesReceived = 0; + break; + default: + perror("Unhandled error from recvfrom()"); + break; + } + + // Reset errno + errno = 0; + } + + // Kill the packet loop if we broke out with a SIGINT + if (sigint_flag) break; + + printf("Received %d bytes\n", bytesReceived); + + // Check for receive errors and break + if (bytesReceived < 0) + { + perror("ERROR in recieving packet\n"); + retVal = 1; + break; + } + + // Is this an LBARD packet? + if (packet[0] == 'L' && + packet[1] == 'B' && + packet[2] == 'A' && + packet[3] == 'R' && + packet[4] == 'D') + { + // Check if the packet is not just a header + if (sizeof(packet) > 5) + { + printf("About to call decode_lbard()\n"); + + // Initialise a buffer to store our decoded LBARD packet in + char lbardResult[8192]; + + // Decode the LABRD packet + // 16 byte offset before analysis to remove packet header + // 32 bytes of Reed-Solomon error correction trimmed from the end + // 1 byte of new line character that is an artifact of data collection removed from the end also + decode_lbard(&packet[16], bytesReceived - 16 - 32 - 1, outFile, myAttachedMeshExtender); + + // Null-terminate the decoded packet buffer + lbardResult[0] = '\0'; + } + } + else // Not an LBARD packet, must be from WiFi + { + // Decode wifi packet and put returned string into NTD text file + decode_wifi(&packet, bytesReceived, outFile); + } + + // Null-terminate the packet buffer + packet[0] = '\0'; + } + + //add final line to file + fprintf(outFile, "@enduml"); + + //run the program to create the graph + //change the arguments to where file location is ect + char *location = args.jarpath; + //get current working directory as this is where the generated textural file will be saved + char cwd[PATH_MAX]; + char command[256]; + getcwd(cwd, sizeof(cwd)); + + //wait to finish writing file + printf("writing diagram text file\n"); + fclose(outFile); + + //call program to make graph + printf("Making diagram in: %s\n", cwd); + snprintf(command, 256, "java -jar \'%s\' \'%s/%s\'", location, cwd, timingDiagramFileName); + //printf("Running following command to make graph\n %s\nPlease wait - Program will finish when diagram is made\n\n", command); + system(command); + + } while (0); + + return retVal; }