1 /*
2  * Copyright 2016, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // Simple program to try running an APF program against a packet.
18 
19 #include <libgen.h>
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 
25 #include "apf_interpreter.h"
26 
27 // Parses hex in "input". Allocates and fills "*output" with parsed bytes.
28 // Returns length in bytes of "*output".
parse_hex(char * input,uint8_t ** output)29 int parse_hex(char* input, uint8_t** output) {
30     int length = strlen(input);
31     if (length & 1) {
32         fprintf(stderr, "Argument not even number of characters: %s\n", input);
33         exit(1);
34     }
35     length >>= 1;
36     *output = malloc(length);
37     if (*output == NULL) {
38         fprintf(stderr, "Out of memory, tried to allocate %d\n", length);
39         exit(1);
40     }
41     for (int i = 0; i < length; i++) {
42         char byte[3] = { input[i*2], input[i*2+1], 0 };
43         char* end_ptr;
44         (*output)[i] = strtol(byte, &end_ptr, 16);
45         if (end_ptr != byte + 2) {
46             fprintf(stderr, "Failed to parse hex %s\n", byte);
47             exit(1);
48         }
49     }
50     return length;
51 }
52 
main(int argc,char * argv[])53 int main(int argc, char* argv[]) {
54     if (argc != 4) {
55         fprintf(stderr,
56                 "Usage: %s <program> <packet> <program age>\n"
57                 "  program:     APF program, in hex\n"
58                 "  packet:      Packet to run through program, in hex\n"
59                 "  program age: Age of program in seconds.\n",
60                 basename(argv[0]));
61         exit(1);
62     }
63     uint8_t* program;
64     uint32_t program_len = parse_hex(argv[1], &program);
65     uint8_t* packet;
66     uint32_t packet_len = parse_hex(argv[2], &packet);
67     uint32_t filter_age = atoi(argv[3]);
68     int ret = accept_packet(program, program_len, packet, packet_len,
69                             filter_age);
70     printf("Packet %sed\n", ret ? "pass" : "dropp");
71     free(program);
72     free(packet);
73     return ret;
74 }