/* Copyright (c) 2012 Erik Shadwick This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include #include #include #include #include #include "program.h" #include "util.h" typedef struct { const char *hostname, *port; FILE *input; } Arguments; int args_parse(int argc, char *argv[], Arguments *args) { int i; #define ERR(mesg) \ { fprintf(stderr, mesg); \ return -1; } memset(args, 0, sizeof(Arguments)); if (argc == 1 || argc > 6) ERR("Usage nf [[-h hostname] -p port] file\n"); for (i = 1; i < argc; i++) { /* Hostname */ if (strcmp(argv[i], "-h") == 0) { if (i + 1 >= argc) ERR("Missing hostname\n"); if (args->hostname) ERR("More than one hostname given\n"); args->hostname = argv[i + 1]; i++; } /* Port */ else if (strcmp(argv[i], "-p") == 0) { if (i + 1 >= argc) ERR("Missing port\n"); if (args->port) ERR("More than one port given\n"); args->port = argv[i + 1]; i++; } /* Input file */ else if (i + 1 == argc) { args->input = fopen(argv[i], "r"); if (!args->input) ERR("Could not open input file\n"); } } if (args->hostname && !args->port) ERR("Hostname given but no port given\n"); if (!args->input) ERR("No input file given\n"); return 0; #undef ERR } int main(int argc, char *argv[]) { Program *program; Arguments args; char *source = NULL; uint32_t length = 0; /* Parse command-line options */ if (args_parse(argc, argv, &args) != 0) { if (args.input) fclose(args.input); return -1; } /* Read source from input */ do { length += 128; source = realloc(source, length); fread(source + length - 128, 1, 128, args.input); } while (!feof(args.input)); /* Create and run the program */ util_init(); program = program_create(source); if (program == NULL) { fprintf(stderr, "There was a problem compiling the source; either " \ "there are unmatching brackets, or more than one pipe was used.\n"); } else { if (args.port) program_connect(program, args.hostname, args.port); program_execute(program); program_destroy(program); } /* Clean up */ util_cleanup(); free(source); if (args.input) fclose(args.input); return 0; }