int main(int argc, char **argv) { int rc = 1; opts.spaces = 2; command_t cmd; command_init(&cmd, argv[0], "1.0.0"); command_option(&cmd , "-v" , "--verbose" , "enable verbose stuff" , set_verbose); command_option(&cmd , "-s" , "--spaces [count]" , "optional number of spaces (defaults to 2)" , set_spaces); command_parse(&cmd, argc, argv); for (int i = 0; i < cmd.argc; ++i) { if (-1 == convert_file(cmd.argv[i])) goto cleanup; } rc = 0; cleanup: command_free(&cmd); return rc; }
int main(int argc, char** argv) { command_t cmd; command_init(&cmd, "dhcore-test", "1.0"); command_option_pos(&cmd, "test", "Choose unit test", TRUE, cmd_gettest); command_parse(&cmd, argc, argv, NULL); if (IS_FAIL(core_init(CORE_INIT_ALL))) { printf("core init error.\n"); return -1; } log_outputconsole(TRUE); if (g_testidx == -1) g_testidx = show_help(); if (g_testidx != -1) g_tests[g_testidx].test_fn(); #if defined(_DEBUG_) core_release(TRUE); #else core_release(FALSE); #endif return 1; }
// The task to process SMS events static void sms_task(iptr_t timer) { //Silence "args not used" warning. (void)timer; int8_t smsIndex = 0; DB(LOG_INFO("\r\nChecking SMS...\r\n")); // Update signal level GSM(updateCSQ()); // Flush SMS buffer GSM(gsmBufferCleanup(&msg)); // Retrive the first SMS into memory GSM(smsIndex = gsmSMSByIndex(&msg, 1)); if (smsIndex==1) { command_parse(&dbg_port.fd, msg.text); DELAY(500); GSM(gsmSMSDel(1)); } // Process SMS commands smsSplitAndParse(msg.from, msg.text); // Restart GSM at each countdown if (--gsmRestartCountdown == 0) { LOG_INFO("\r\nRestarting GSM..."); GSM(gsmPowerOff()); gsmRestartCountdown = GSM_RESTART_COUNTDOWN; } // Reschedule this timer synctimer_add(&sms_tmr, &timers_lst); }
int command_parse_and_dispatch(const char * cmd) { char* args[MAX_ARGC]; int tokens = command_parse(cmd, args); if (tokens == -1) return -1; return command_dispatch(tokens, (const char **) args); }
void command_prompt(void) { printf("Entering recovery mode, starting command prompt\n"); while(1) { char buffer[256]; safe_gets("] ", buffer, 256); command_parse(buffer); } }
static void acm_parse(int32_t _amt) { int i = 0; char **argv; int argc; char scratch[ACM_BUFFER_SIZE]; for(; i < _amt; i++) { if(acm_recv_buffer[i] == '\n' || acm_recv_buffer[i] == '\r') { _amt = i; break; } } acm_recv_buffer[_amt] = 0; memcpy(scratch, acm_recv_buffer, _amt+1); argv = command_parse(scratch, &argc); if(argc >= 3 && strcmp(argv[0], "sendfile") == 0) { acm_busy = TRUE; acm_file_ptr = (char*)parseNumber(argv[1]); acm_file_recv_left = parseNumber(argv[2]); received_file_size = acm_file_recv_left; bufferPrintf("ACM: Started receiving file at 0x%08x - 0x%08x (%d bytes).\n", acm_file_ptr, acm_file_ptr + acm_file_recv_left, acm_file_recv_left); } else if(argc >= 3 && strcmp(argv[0], "recvfile") == 0) { acm_busy = TRUE; acm_file_ptr = (char*)parseNumber(argv[1]); acm_file_send_left = parseNumber(argv[2]); bufferPrintf("ACM: Started sending file at 0x%08x - 0x%08x (%d bytes).\n", acm_file_ptr, acm_file_ptr + acm_file_send_left, acm_file_send_left); int amt = sprintf(acm_send_buffer, "ACM: Starting File: %d %d\n", (uint32_t)acm_file_ptr, acm_file_send_left); usb_send_bulk(ACM_EP_SEND, acm_send_buffer, amt); } else { bufferPrintf("ACM: Starting %s\n", acm_recv_buffer); if(command_run(argc, argv) == 0) bufferPrintf("ACM: Done: %s\n", acm_recv_buffer); else bufferPrintf("ACM: Unknown command: %s\n", argv[0]); } free(argv); EnterCriticalSection(); // Deliberately unended. usb_receive_bulk(ACM_EP_RECV, acm_recv_buffer, acm_usb_mps); task_stop(); }
/* Function: test_redirect Test commands with io redirect */ void test_redirect() { #ifdef DEBUG_TEST printf("TEST: Checking I/O redirecting\n"); #endif cmd = command_parse("a < b > c\n"); assert(cmd != NULL); assert(cmd->token >= 1); assert(strcmp(cmd->argv[0], "a") == 0); assert(strcmp(cmd->infile, "b") == 0); assert(strcmp(cmd->outfile, "c") == 0); assert(cmd->fdmode == (O_RDWR|O_TRUNC)); command_free(cmd); cmd = command_parse("a<b>> c\n"); assert(cmd != NULL); assert(cmd->token >= 1); assert(strcmp(cmd->argv[0], "a") == 0); assert(strcmp(cmd->infile, "b") == 0); assert(strcmp(cmd->outfile, "c") == 0); assert(cmd->fdmode == (O_RDWR|O_APPEND)); command_free(cmd); cmd = command_parse("a<b>c\n"); assert(cmd != NULL); assert(cmd->token >= 1); assert(strcmp(cmd->argv[0], "a") == 0); assert(strcmp(cmd->infile, "b") == 0); assert(strcmp(cmd->outfile, "c") == 0); assert(cmd->fdmode == (O_RDWR|O_TRUNC)); command_free(cmd); cmd = command_parse("a <b >>c\n"); assert(cmd != NULL); assert(cmd->token >= 1); assert(strcmp(cmd->argv[0], "a") == 0); assert(strcmp(cmd->infile, "b") == 0); assert(strcmp(cmd->outfile, "c") == 0); assert(cmd->fdmode == (O_RDWR|O_APPEND)); command_free(cmd); }
void Arguments::parse(int argc, char* argv[]) { // commander internal data structure command_t cmd; command_init(&cmd, argv[0], VERSION); command_option(&cmd, "-v", "--version", "Show game version and build date", version); command_option(&cmd, "-h", "--help", "Show instructions", help); command_parse(&cmd, argc, argv); command_free(&cmd); }
TEST(test_command_parse, parse_different_commands) { struct command_description *ret_fct; // Unkown ret_fct = command_parse("unknown_command", commands); ASSERT_EQ(NULL, ret_fct); // No arguments ret_fct = command_parse("no_arguments", commands); ASSERT_EQ(&commands[0], ret_fct); // One argument with valid value ret_fct = command_parse("one_argument 12", commands); ASSERT_EQ(&commands[1], ret_fct); // One argument without valid value ret_fct = command_parse("one_argument invalid", commands); ASSERT_EQ(NULL, ret_fct); // Test parsing multiple arguments ret_fct = command_parse("many_arguments 3.14 lala 42 test str", commands); ASSERT_EQ(&commands[2], ret_fct); // with invalid value ret_fct = command_parse("many_arguments 25 lala 1.414 test str", commands); ASSERT_EQ(NULL, ret_fct); }
/* Function: test_pipe Test command with pipes */ void test_pipe() { #ifdef DEBUG_TEST printf("TEST: Checking pipes\n"); #endif cmd = command_parse("a | b | c \n"); assert(cmd != NULL); assert(strcmp(cmd->argv[0], "a") == 0); assert(strcmp(cmd->next->argv[0], "b") == 0); assert(strcmp(cmd->next->next->argv[0], "c") == 0); command_free(cmd); cmd = command_parse("a| b |c \n"); assert(cmd != NULL); assert(strcmp(cmd->argv[0], "a") == 0); assert(strcmp(cmd->next->argv[0], "b") == 0); assert(strcmp(cmd->next->next->argv[0], "c") == 0); command_free(cmd); cmd = command_parse("a|b|c \n"); assert(cmd != NULL); assert(strcmp(cmd->argv[0], "a") == 0); assert(strcmp(cmd->next->argv[0], "b") == 0); assert(strcmp(cmd->next->next->argv[0], "c") == 0); command_free(cmd); cmd = command_parse("a<in|b|c > out &\n"); assert(cmd != NULL); assert(strcmp(cmd->argv[0], "a") == 0); assert(strcmp(cmd->infile, "in") == 0); assert(strcmp(cmd->next->argv[0], "b") == 0); assert(strcmp(cmd->next->next->argv[0], "c") == 0); assert(strcmp(cmd->next->next->outfile, "out") == 0); assert(cmd->background == TRUE); assert(cmd->next->background == TRUE); assert(cmd->next->next->background == TRUE); command_free(cmd); }
/* Function: test_standard Several standard command */ void test_standard() { #ifdef DEBUG_TEST printf("TEST: Checking standard command\n"); #endif cmd = command_parse("cat testfile1 testfile2\n"); assert(cmd != NULL); assert(cmd->token >= 3); assert(strcmp(cmd->argv[0], "cat") == 0); assert(strcmp(cmd->argv[1], "testfile1") == 0); assert(strcmp(cmd->argv[2], "testfile2") == 0); command_free(cmd); cmd = command_parse("echo line&\n"); assert(cmd != NULL); assert(cmd->token >= 2); assert(cmd->background == TRUE); assert(strcmp(cmd->argv[0], "echo") == 0); assert(strcmp(cmd->argv[1], "line") == 0); command_free(cmd); }
static Command *sam_parse(Vis *vis, const char *cmd, enum SamError *err) { const char **s = &cmd; Command *c = command_parse(vis, s, 0, err); if (!c) return NULL; Command *sel = command_new("s"); if (!sel) { command_free(c); return NULL; } sel->cmd = c; sel->cmddef = &cmddef_select; return sel; }
int main1(int argc, char **argv) { command_t cmd; command_init(&cmd, argv[0], "0.0.1"); command_option(&cmd, "-v", "--verbose", "enable verbose stuff", verbose); command_option(&cmd, "-r", "--required <arg>", "required arg", required); command_option(&cmd, "-o", "--optional [arg]", "optional arg", optional); command_parse(&cmd, argc, argv); printf("additional args:\n"); for (int i = 0; i < cmd.argc; ++i) { printf(" - '%s'\n", cmd.argv[i]); } command_free(&cmd); return 0; }
/* Function: direct_input */ void direct_input() { #ifdef DEBUG_TEST printf("TEST: Read and parse command from STDIN\n"); #endif char buffer[CMD_MAX]; while(TRUE) { printf("# "); fgets(buffer, CMD_MAX, stdin); cmd = command_parse(buffer); command_print(cmd); command_free(cmd); } }
int main(int argc, char **argv){ command_t cmd; command_init(&cmd, argv[0], "0.0.1"); command_option(&cmd, "-d", "--detached", "spawn a detached process", verbose); command_option(&cmd, "-i", "--ipc [arg]", "listen to a pipe", required); command_option(&cmd, "-f", "--fd [arg]", "listen and track a file descriptor", required); command_option(&cmd, "-a", "--auth [arg]", "fd to get authorization information from", optional); command_parse(&cmd, argc, argv); printf("additional args:\n"); for (int i = 0; i < cmd.argc; ++i) { printf(" - '%s'\n", cmd.argv[i]); } command_free(&cmd); return 0; }
int main(int argc, char **argv){ monitor_t monitor; monitor.pidfile = NULL; monitor.mon_pidfile = NULL; monitor.on_error = NULL; monitor.logfile = "mon.log"; monitor.daemon = 0; monitor.sleepsec = 1; command_t program; program.data = &monitor; command_init(&program, "mon", VERSION); command_option(&program, "-l", "--log <path>", "specify logfile [mon.log]", on_log); command_option(&program, "-s", "--sleep <sec>", "sleep seconds before re-executing [1]", on_sleep); command_option(&program, "-S", "--status", "check status of --pidfile", on_status); command_option(&program, "-p", "--pidfile <path>", "write pid to <path>", on_pidfile); command_option(&program, "-m", "--mon-pidfile <path>", "write mon(1) pid to <path>", on_mon_pidfile); command_option(&program, "-P", "--prefix <str>", "add a log prefix", on_prefix); command_option(&program, "-d", "--daemonize", "daemonize the program", on_daemonize); command_option(&program, "-e", "--on-error <cmd>", "execute <cmd> on errors", on_error); command_parse(&program, argc, argv); // command required if (!program.argc) error("<cmd> required"); const char *cmd = program.argv[0]; // signals signal(SIGTERM, graceful_exit); signal(SIGQUIT, graceful_exit); // daemonize if (monitor.daemon) { daemonize(); redirect_stdio_to(monitor.logfile); } // write mon pidfile if (monitor.mon_pidfile) { log("write mon pid to %s", monitor.mon_pidfile); write_pidfile(monitor.mon_pidfile, getpid()); } start(cmd, &monitor); return 0; }
int main(void) { char line[MAXLINE]; int i; char ** arglist; struct sigaction act; signal(SIGINT, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGTSTP, SIG_IGN); act.sa_handler = child_handler; sigfillset(&act.sa_mask); act.sa_flags = SA_RESTART; sigaction(SIGCHLD,&act,NULL); fputs("minishell> ",stdout); while(fgets(line,MAXLINE,stdin)) { if(!strncmp(line,"exit",4)) { exit(0); } if(arglist=command_parse(line)) { if(!check_builtin(arglist)) { // for(i=0;arglist[i];i++) // { // printf("[%d] : %s\n", i,arglist[i]); exec_command(arglist); // } } command_freelist(arglist); } fputs("minishell> ",stdout); } return 0; }
int main(int argc, const char **argv) { puts("Hello World"); /* prints Hello World */ command_init(&cmd, argv[0], "0.0.1", "[options] command"); command_option(&cmd, "-w", "--wait <ms>", "wait before spawning, default 3100ms", wait_handler); command_option(&cmd, "-m", "--multicast-wait <ms>", "wait between multicasts, default 1000ms", multicast_wait_handler); command_parse(&cmd, argc, argv); printf("additional args:\n"); for (int i = 0; i < cmd.argc; ++i) { printf(" - '%s'\n", cmd.argv[i]); } loop(2345, inet_addr("239.0.0.0")); command_free(&cmd); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { #ifdef _WIN32 opts.dir = ".\\deps"; #else opts.dir = "./deps"; #endif opts.verbose = 1; opts.dev = 0; command_t program; command_init(&program , "clib-install" , CLIB_VERSION); program.usage = "[options] [name ...]"; command_option(&program , "-o" , "--out <dir>" , "change the output directory [deps]" , setopt_dir); command_option(&program , "-q" , "--quiet" , "disable verbose output" , setopt_quiet); command_option(&program , "-d" , "--dev" , "install development dependencies" , setopt_dev); command_parse(&program, argc, argv); int code = 0 == program.argc ? install_local_packages() : install_packages(program.argc, program.argv); command_free(&program); return code; }
TEST(test_command_parse, too_big_number_of_arguments) { struct command_description commands[] = { {"large_format_33" " %d %d %d %d %d %d %d %d" " %d %d %d %d %d %d %d %d" " %d %d %d %d %d %d %d %d" " %d %d %d %d %d %d %d %d" " %d", 33, (cmd_fct_t) 1}, {NULL, 0, NULL} }; struct command_description *ret_fct; ret_fct = command_parse("large_format_33" " 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", commands); ASSERT_EQ(NULL, ret_fct); }
int main(int argc, char *argv[]) { command_t program; command_init(&program, "clib-search", CLIB_VERSION); program.usage = "[options] [query ...]"; command_parse(&program, argc, argv); for (int i = 0; i < program.argc; i++) case_lower(program.argv[i]); char *html = wiki_html_cache(); if (NULL == html) { command_free(&program); fprintf(stderr, "Failed to fetch wiki HTML\n"); return 1; } list_t *pkgs = wiki_registry_parse(html); free(html); list_node_t *node; list_iterator_t *it = list_iterator_new(pkgs, LIST_HEAD); printf("\n"); while ((node = list_iterator_next(it))) { wiki_package_t *pkg = (wiki_package_t *) node->val; if (matches(program.argc, program.argv, pkg)) { cc_fprintf(CC_FG_DARK_CYAN, stdout, " %s\n", pkg->repo); printf(" url: "); cc_fprintf(CC_FG_DARK_GRAY, stdout, "%s\n", pkg->href); printf(" desc: "); cc_fprintf(CC_FG_DARK_GRAY, stdout, "%s\n", pkg->description); printf("\n"); } wiki_package_free(pkg); } list_iterator_destroy(it); list_destroy(pkgs); command_free(&program); return 0; }
int main(int argc, char **argv) { filter.executables = true; filter.utilities = true; command_t program; command_init(&program, "clib-search", CLIB_SEARCH_VERSION); program.usage = "[options] [query ...]"; command_option(&program, "-a", "--author <author>", "filter by author", author); command_option(&program, "-e", "--executables", "filter by executables", executables); command_option(&program, "-u", "--utilities", "filter by utilities", utilities); command_parse(&program, argc, argv); char *html = wiki_html_cache(); if (NULL == html) { fprintf(stderr, "Failed to fetch wiki HTML\n"); return 1; } list_t *pkgs = wiki_registry_parse(html); list_node_t *node; list_iterator_t *it = list_iterator_new(pkgs, LIST_HEAD); while ((node = list_iterator_next(it))) { package_t *pkg = (package_t *) node->val; if (matches(program.argc, program.argv, pkg)) { printf(" \033[36m%s\033[m\n", pkg->repo); printf(" url: \033[90m%s\033[m\n", pkg->href); printf(" desc: \033[90m%s\033[m\n", pkg->description); printf("\n"); } } list_iterator_destroy(it); list_destroy(pkgs); command_free(&program); return 0; }
int main(int argc, char *argv[]) { cli_init(); log_init(); thread_init(); cmd_init(); dev_addr_mgr_init(); addr_sock_init(); socket_init(); dev_router_init(); cli_commands_init(); broadcast_msg_t msg; dev_addr_mgr_add_support_dev_type(1); dev_addr_mgr_set_network_type(NETWORK_TYPE_CENTER); dev_addr_mgr_set_addr_mac(0x89ABCDE0); dev_router_set_mac_local(0x89ABCDE0); #ifdef TEST_CLIENT ex_memzero_one(&msg); strcpy(msg.dev_name, "1004"); msg.router_list_lens[0] = 3; msg.router_list_lens[1] = 3; msg.router_list_lens[2] = 0; msg.router_list_lens[3] = 0; msg.router_cnt = 7; msg.router_list_cnt = 2; msg.network_nodes[0].dev_type = 1; msg.network_nodes[0].addr_mac = 0x89ABCDE0; msg.network_nodes[0].subnet_cnt = 4; msg.network_nodes[0].network_type = NETWORK_TYPE_ROUTER; strcpy(msg.network_nodes[0].dev_name, "1004"); msg.network_nodes[1].dev_type = 1; msg.network_nodes[1].addr_mac = 0x89ABCDE1; msg.network_nodes[1].subnet_cnt = 4; msg.network_nodes[1].network_type = NETWORK_TYPE_ROUTER; strcpy(msg.network_nodes[1].dev_name, "1003"); msg.network_nodes[2].dev_type = 1; msg.network_nodes[2].addr_mac = 0x89ABCDE2; msg.network_nodes[2].subnet_cnt = 4; msg.network_nodes[2].network_type = NETWORK_TYPE_ROUTER; strcpy(msg.network_nodes[2].dev_name, "1002"); msg.network_nodes[3].dev_type = 1; msg.network_nodes[3].addr_mac = 0x89ABCDE3; msg.network_nodes[3].subnet_cnt = 4; msg.network_nodes[3].network_type = NETWORK_TYPE_ROUTER; strcpy(msg.network_nodes[3].dev_name, "1001"); msg.network_nodes[4].dev_type = 1; msg.network_nodes[4].addr_mac = 0x89ABCDE4; msg.network_nodes[4].subnet_cnt = 4; msg.network_nodes[4].network_type = NETWORK_TYPE_ROUTER; strcpy(msg.network_nodes[4].dev_name, "1005"); msg.network_nodes[5].dev_type = 1; msg.network_nodes[5].addr_mac = 0x89ABCDE5; msg.network_nodes[5].subnet_cnt = 4; msg.network_nodes[5].network_type = NETWORK_TYPE_ROUTER; strcpy(msg.network_nodes[5].dev_name, "1006"); msg.network_nodes[6].dev_type = 1; msg.network_nodes[6].addr_mac = 0x89ABCDE6; msg.network_nodes[6].subnet_cnt = 4; msg.network_nodes[6].network_type = NETWORK_TYPE_ROUTER; strcpy(msg.network_nodes[6].dev_name, "1007"); #endif socket_listen_async(50002); socket_listen_cli(49999); socket_recv_start(); #ifdef TEST_SERVER socket_bc_tx_start("test", 50000, 50001, 50002); #endif #ifdef TEST_CLIENT socket_bc_rx_start("test", 50000, 50001, &msg); #endif #if 0 cstr *json = cstr_new(); int fd = 0; fd = socket_cli_send_request("127.0.0.1", 49999, "test"); socket_cli_recv_response(fd, json); cstr_clear(json); fd = socket_cli_send_request("127.0.0.1", 49999, "test f**k"); socket_cli_recv_response(fd, json); cstr_clear(json); fd = socket_cli_send_request("127.0.0.1", 49999, "f**k f**k f**k you test f**k"); socket_cli_recv_response(fd, json); cstr_free(json); #endif cli_loop(); dev_addr_mgr_release(); socket_release(); cmd_release(); thread_release(); log_release(); cli_release(); #if 0 cli_cmd_t cmd; int i = 0; command_init(&cmd, argv[0], "0.0.1"); command_option(&cmd, "-v", "--verbose", "enable verbose stuff", verbose); command_option(&cmd, "-r", "--required <arg>", "required arg", required); command_option(&cmd, "-o", "--optional [arg]", "optional arg", optional); command_parse(&cmd, argc, argv); printf("additional args:\n"); for (i = 0; i < cmd.argc; ++i) { printf(" - '%s'\n", cmd.argv[i]); } command_free(&cmd); #endif return 0; }
int main (int argc, char **argv) { unsigned char *buf; long bufSize = 0; unsigned char *original; long originalSize = 0; unsigned char *originalGray; long originalGraySize = 0; unsigned char *compressed = NULL; unsigned long compressedSize = 0; unsigned char *compressedGray; long compressedGraySize = 0; unsigned char *tmpImage; int width, height; unsigned char *metaBuf; unsigned int metaSize = 0; // Parse commandline options command_t cmd; command_init(&cmd, argv[0], "1.0.1"); cmd.usage = "[options] input.jpg compressed-output.jpg"; command_option(&cmd, "-t", "--target [arg]", "Set target SSIM [0.9999]", setTarget); command_option(&cmd, "-q", "--quality [arg]", "Set a quality preset: low, medium, high, veryhigh [medium]", setQuality); command_option(&cmd, "-n", "--min [arg]", "Minimum JPEG quality [40]", setMinimum); command_option(&cmd, "-m", "--max [arg]", "Maximum JPEG quality [95]", setMaximum); command_option(&cmd, "-l", "--loops [arg]", "Set the number of runs to attempt [6]", setAttempts); command_option(&cmd, "-p", "--progressive", "Set progressive JPEG output", setProgressive); command_option(&cmd, "-s", "--strip", "Strip metadata", setStrip); command_option(&cmd, "-d", "--defish [arg]", "Set defish strength [0.0]", setDefish); command_option(&cmd, "-z", "--zoom [arg]", "Set defish zoom [1.0]", setZoom); command_parse(&cmd, argc, argv); if (cmd.argc < 2) { command_help(&cmd); return 255; } // Read original bufSize = readFile((char *) cmd.argv[0], (void **) &buf); if (!bufSize) { return 1; } // Decode the JPEG originalSize = decodeJpeg(buf, bufSize, &original, &width, &height, JCS_RGB); if (defishStrength) { fprintf(stderr, "Defishing...\n"); tmpImage = malloc(width * height * 3); defish(original, tmpImage, width, height, 3, defishStrength, defishZoom); free(original); original = tmpImage; } // Convert RGB input into Y originalGraySize = width * height; originalGray = malloc(originalGraySize); int stride = width * 3; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // Y = 0.299R + 0.587G + 0.114B originalGray[y * width + x] = original[y * stride + x * 3] * 0.299 + original[y * stride + x * 3 + 1] * 0.587 + original[y * stride + x * 3 + 2] * 0.114 + 0.5; } } // Read metadata (EXIF / IPTC / XMP tags) if (getMetadata(buf, bufSize, &metaBuf, &metaSize, COMMENT)) { fprintf(stderr, "File already processed by jpeg-recompress!\n"); return 2; } if (strip) { // Pretend we have no metadata metaSize = 0; } else { fprintf(stderr, "Metadata size is %ukb\n", metaSize / 1024); } if (!originalSize || !originalGraySize) { return 1; } free(buf); // Do a binary search to find the optimal encoding quality for the // given target SSIM value. int min = jpegMin, max = jpegMax; for (int attempt = attempts - 1; attempt >= 0; --attempt) { int quality = min + (max - min) / 2; // Recompress to a new quality level (progressive only on last run if // it was requested, as this saves time) compressedSize = encodeJpeg(&compressed, original, width, height, JCS_RGB, quality, (attempt == 0) ? progressive : 0); // Load compressed luma for quality comparison compressedGraySize = decodeJpeg(compressed, compressedSize, &compressedGray, &width, &height, JCS_GRAYSCALE); // Measure structural similarity (SSIM) float ssim = iqa_ssim(originalGray, compressedGray, width, height, width, 0, 0); fprintf(stderr, "ssim at q=%i (%i - %i): %f\n", quality, min, max, ssim); if (ssim < target) { if (compressedSize >= bufSize) { fprintf(stderr, "Output file would be larger than input, aborting!\n"); free(compressed); free(compressedGray); return 1; } // Too distorted, increase quality min = quality + 1; } else { // Higher SSIM than required, decrease quality max = quality - 1; } // If we aren't done yet, then free the image data if (attempt) { free(compressed); free(compressedGray); } } // Calculate and show savings, if any int percent = (compressedSize + metaSize) * 100 / bufSize; unsigned long saved = (bufSize > compressedSize) ? bufSize - compressedSize - metaSize : 0; fprintf(stderr, "New size is %i%% of original (saved %lu kb)\n", percent, saved / 1024); if (compressedSize >= bufSize) { fprintf(stderr, "Output file is larger than input, aborting!\n"); return 1; } // Write output FILE *file; if (strcmp("-", cmd.argv[1]) == 0) { file = stdout; } else { file = fopen(cmd.argv[1], "wb"); } fwrite(compressed, 20, 1, file); /* 0xffd8 and JFIF marker */ // Write comment so we know not to reprocess this file // in the future if it gets passed in again. // 0xfffe (COM marker), two-byte big-endian length, string fputc(0xff, file); fputc(0xfe, file); fputc(0x00, file); fputc(32, file); fwrite(COMMENT, 30, 1, file); // Write metadata markers if (!strip) { fwrite(metaBuf, metaSize, 1, file); } // Write image data fwrite(compressed + 20, compressedSize - 20, 1, file); fclose(file); // Cleanup command_free(&cmd); if (!strip) { free(metaBuf); } free(compressed); free(original); free(originalGray); free(compressedGray); return 0; }
static gboolean _command_parse_command_function (const char* line) { gboolean result; result = command_parse (line); return result; }
/* * command_line_parse(parsestate, in_parens) * * Parses a command line from 'input' into a linked list of command_t * structures. The head of the linked list is returned, or NULL is * returned on error. * If 'in_parens != 0', then command_line_parse() is being called recursively * from command_parse(). A right parenthesis should end the "command line". * But at the top-level command line, when 'in_parens == 0', a right * parenthesis is an error. */ command_t * command_line_parse(parsestate_t *parsestate, int in_parens) { command_t *prev_cmd = NULL; command_t *head = NULL; command_t *cmd; token_t token; int r; // This loop has to deal with command syntax in a smart way. // Here's a non exhaustive list of the behavior it should implement // when 'in_parens == 0'. // COMMAND => OK // COMMAND ; => OK // COMMAND && COMMAND => OK // COMMAND && => error (can't end with &&) // COMMAND ) => error (but OK if "in_parens") while (1) { // Parse the next command. cmd = command_parse(parsestate); if (!cmd) // Empty commands are errors. goto error; // Link the command up to the command line. if (prev_cmd) prev_cmd->next = cmd; else head = cmd; prev_cmd = cmd; // EXERCISE: Fetch the next token to see how to connect this // command with the next command. React to errors with // 'goto error'. The ";" and "&" tokens may require special // handling, since unlike other special tokens, they can end // the command line. parse_gettoken(parsestate, &token); if (token.type == TOK_NORMAL) printf("parse token error"); cmd->controlop = token.type; /* Your code here */ switch (token.type) { case TOK_SEMICOLON: case TOK_AMPERSAND: parse_gettoken(parsestate, &token); if (token.type != TOK_END) parse_ungettoken(parsestate); else goto done; break; case TOK_CLOSE_PAREN: if (in_parens == PARENS_IN) { cmd->controlop = CMD_END; goto done; } else goto error; break; case TOK_END: goto done; default: ; } } done: // EXERCISE: Check that the command line ends properly. /* if (in_parens == PARENS_OUT) { if (strlen(parsestate->position) != 0) { printf("strlen %d\n", strlen(parsestate->position)); perror("line end error"); exit(1); } }*/ /* Your code here */ return head; error: command_free(head); return NULL; }
int main (int argc, char **argv) { unsigned char *buf; long bufSize = 0; unsigned char *original; long originalSize = 0; unsigned char *originalGray = NULL; long originalGraySize = 0; unsigned char *compressed = NULL; unsigned long compressedSize = 0; unsigned char *compressedGray; long compressedGraySize = 0; unsigned char *tmpImage; int width, height; unsigned char *metaBuf; unsigned int metaSize = 0; FILE *file; // Parse commandline options command_t cmd; command_init(&cmd, argv[0], VERSION); cmd.usage = "[options] input.jpg compressed-output.jpg"; command_option(&cmd, "-t", "--target [arg]", "Set target quality [0.9999]", setTarget); command_option(&cmd, "-q", "--quality [arg]", "Set a quality preset: low, medium, high, veryhigh [medium]", setQuality); command_option(&cmd, "-n", "--min [arg]", "Minimum JPEG quality [40]", setMinimum); command_option(&cmd, "-x", "--max [arg]", "Maximum JPEG quality [95]", setMaximum); command_option(&cmd, "-l", "--loops [arg]", "Set the number of runs to attempt [6]", setAttempts); command_option(&cmd, "-a", "--accurate", "Favor accuracy over speed", setAccurate); command_option(&cmd, "-m", "--method [arg]", "Set comparison method to one of 'mpe', 'ssim', 'ms-ssim', 'smallfry' [ssim]", setMethod); command_option(&cmd, "-s", "--strip", "Strip metadata", setStrip); command_option(&cmd, "-d", "--defish [arg]", "Set defish strength [0.0]", setDefish); command_option(&cmd, "-z", "--zoom [arg]", "Set defish zoom [1.0]", setZoom); command_option(&cmd, "-r", "--ppm", "Parse input as PPM instead of JPEG", setPpm); command_option(&cmd, "-c", "--no-copy", "Disable copying files that will not be compressed", setCopyFiles); command_option(&cmd, "-p", "--no-progressive", "Disable progressive encoding", setNoProgressive); command_parse(&cmd, argc, argv); if (cmd.argc < 2) { command_help(&cmd); return 255; } if (method == UNKNOWN) { fprintf(stderr, "Invalid method!"); command_help(&cmd); return 255; } // No target passed, use preset! if (!target) { setTargetFromPreset(); } // Read original bufSize = readFile((char *) cmd.argv[0], (void **) &buf); if (!bufSize) { return 1; } if (!ppm) { // Decode the JPEG originalSize = decodeJpeg(buf, bufSize, &original, &width, &height, JCS_RGB); } else { // Decode the PPM originalSize = decodePpm(buf, bufSize, &original, &width, &height); } if (defishStrength) { fprintf(stderr, "Defishing...\n"); tmpImage = malloc(width * height * 3); defish(original, tmpImage, width, height, 3, defishStrength, defishZoom); free(original); original = tmpImage; } // Convert RGB input into Y originalGraySize = grayscale(original, &originalGray, width, height); if (!ppm) { // Read metadata (EXIF / IPTC / XMP tags) if (getMetadata(buf, bufSize, &metaBuf, &metaSize, COMMENT)) { fprintf(stderr, "File already processed by jpeg-recompress!\n"); if (copyFiles) { file = openOutput(cmd.argv[1]); fwrite(buf, bufSize, 1, file); fclose(file); free(buf); return 0; } else { free(buf); return 2; } } } if (strip) { // Pretend we have no metadata metaSize = 0; } else { fprintf(stderr, "Metadata size is %ukb\n", metaSize / 1024); } if (!originalSize || !originalGraySize) { return 1; } // Do a binary search to find the optimal encoding quality for the // given target SSIM value. int min = jpegMin, max = jpegMax; for (int attempt = attempts - 1; attempt >= 0; --attempt) { float metric; int quality = min + (max - min) / 2; int progressive = attempt ? 0 : !noProgressive; int optimize = accurate ? 1 : (attempt ? 0 : 1); // Recompress to a new quality level, without optimizations (for speed) compressedSize = encodeJpeg(&compressed, original, width, height, JCS_RGB, quality, progressive, optimize); // Load compressed luma for quality comparison compressedGraySize = decodeJpeg(compressed, compressedSize, &compressedGray, &width, &height, JCS_GRAYSCALE); if (!compressedGraySize) { fprintf(stderr, "Unable to decode file that was just encoded!\n"); return 1; } if (!attempt) { fprintf(stderr, "Final optimized "); } // Measure quality difference switch (method) { case MS_SSIM: metric = iqa_ms_ssim(originalGray, compressedGray, width, height, width, 0); fprintf(stderr, "ms-ssim"); break; case SMALLFRY: metric = smallfry_metric(originalGray, compressedGray, width, height); fprintf(stderr, "smallfry"); break; case MPE: metric = meanPixelError(originalGray, compressedGray, width, height, 1); fprintf(stderr, "mpe"); break; case SSIM: default: metric = iqa_ssim(originalGray, compressedGray, width, height, width, 0, 0); fprintf(stderr, "ssim"); break; } if (attempt) { fprintf(stderr, " at q=%i (%i - %i): %f\n", quality, min, max, metric); } else { fprintf(stderr, " at q=%i: %f\n", quality, metric); } if (metric < target) { if (compressedSize >= bufSize) { fprintf(stderr, "Output file would be larger than input!\n"); free(compressed); free(compressedGray); if (copyFiles) { file = openOutput(cmd.argv[1]); fwrite(buf, bufSize, 1, file); fclose(file); free(buf); return 0; } else { free(buf); return 1; } } switch (method) { case SSIM: case MS_SSIM: case SMALLFRY: // Too distorted, increase quality min = quality + 1; break; case MPE: // Higher than required, decrease quality max = quality - 1; break; } } else { switch (method) { case SSIM: case MS_SSIM: case SMALLFRY: // Higher than required, decrease quality max = quality - 1; break; case MPE: // Too distorted, increase quality min = quality + 1; break; } } // If we aren't done yet, then free the image data if (attempt) { free(compressed); free(compressedGray); } } free(buf); // Calculate and show savings, if any int percent = (compressedSize + metaSize) * 100 / bufSize; unsigned long saved = (bufSize > compressedSize) ? bufSize - compressedSize - metaSize : 0; fprintf(stderr, "New size is %i%% of original (saved %lu kb)\n", percent, saved / 1024); if (compressedSize >= bufSize) { fprintf(stderr, "Output file is larger than input, aborting!\n"); return 1; } // Open output file for writing file = openOutput(cmd.argv[1]); // Write output fwrite(compressed, 20, 1, file); /* 0xffd8 and JFIF marker */ // Write comment so we know not to reprocess this file // in the future if it gets passed in again. // 0xfffe (COM marker), two-byte big-endian length, string fputc(0xff, file); fputc(0xfe, file); fputc(0x00, file); fputc(32, file); fwrite(COMMENT, 30, 1, file); // Write metadata markers if (!strip && !ppm) { fwrite(metaBuf, metaSize, 1, file); } // Write image data fwrite(compressed + 20, compressedSize - 20, 1, file); fclose(file); // Cleanup command_free(&cmd); if (!strip && !ppm) { free(metaBuf); } free(compressed); free(original); free(originalGray); return 0; }
int main(int argc, char** argv) { struct paki_args args; // read arguments memset(&args, 0x00, sizeof(args)); args.compress_mode = COMPRESS_NORMAL; command_t cmd; command_init(&cmd, argv[0], VERSION); command_option_pos(&cmd, "pakfile", "pakfile (.pak)", 0, cmdline_pakfile); command_option_pos(&cmd, "path", "path to input directory (for compress mode) or" " path to a file in pakfile (for extract mode)", 1, cmdline_path); command_option(&cmd, "-v", "--verbose", "enable verbose mode", cmdline_verbose); command_option(&cmd, "-l", "--list", "list files in pak", cmdline_list); command_option(&cmd, "-x", "--extract", "extract a file from pak", cmdline_extract); command_option(&cmd, "-c", "--compress", "compress a directory into pak", cmdline_compress); command_option(&cmd, "-z", "--zmode <mode>", "define compression mode, " "compression modes are (none, normal, best, fast)", cmdline_compressmode); cmd.data = &args; command_parse(&cmd, argc, argv, NULL); command_free(&cmd); core_init(CORE_INIT_ALL); log_outputconsole(TRUE); /* check for arguments validity */ if (args.pakfile[0] == 0 || ((BIT_CHECK(args.usage, PAKI_USAGE_EXTRACT) + BIT_CHECK(args.usage, PAKI_USAGE_COMPRESS) + BIT_CHECK(args.usage, PAKI_USAGE_LIST)) != 1)) { printf(TERM_BOLDRED "Invalid arguments\n" TERM_RESET); core_release(FALSE); return -1; } if (BIT_CHECK(args.usage, PAKI_USAGE_EXTRACT) || BIT_CHECK(args.usage, PAKI_USAGE_COMPRESS)) { if (str_isempty(args.path)) { printf(TERM_BOLDRED "'path' argument is not provided\n" TERM_RESET); core_release(FALSE); return -1; } } /* creating archive (-c flag) */ if (BIT_CHECK(args.usage, PAKI_USAGE_COMPRESS)) { save_pak(&args); } else if(BIT_CHECK(args.usage, PAKI_USAGE_EXTRACT)) { load_pak(&args); } else if(BIT_CHECK(args.usage, PAKI_USAGE_LIST)) { list_pak(&args); } #if defined(_DEBUG_) core_release(TRUE); #else core_release(FALSE); #endif return 0; }
int put_request(struct net_t *n, struct list_t *userName, char *fileName, char *saveLoc) { int filesize; FILE *f; char buf[RCVBUFSIZE]; char *inBuf; int dataSize = 0; struct link_t *templink; struct command_t * cmd; char *filedata; // Setup packet header buf[0] = CMD_PUT; buf[1] = STAT_OK; dataSize += 2; // Add all usernames and filename to packet templink = userName->head; while(templink != NULL){ strncpy(buf + dataSize, templink->item, strlen(templink->item)); dataSize += (strlen(templink->item)); if(templink != userName->tail) { buf[dataSize] = ','; dataSize ++; } templink = templink->next; } buf[dataSize] = ':'; dataSize ++; strncpy(buf + dataSize, fileName, strlen(fileName)); dataSize += (strlen(fileName)); // Sending request packet to the server net_send_tcp(n->sock, buf, dataSize); // Recieve reply from server inBuf = net_recv_tcp(n->sock); // Make sure that packet type is CMD_PUT if(inBuf[0] != CMD_PUT) { printf("Error: Recieved unexpected packet type\n"); return -1; } // Check for errors in the packet status if(inBuf[1] == STAT_BAD_PERM) { printf("Error: Improper permissions, now quitting\n"); return -1; }else if(inBuf[1] == STAT_MALF_REQ) { printf("Error: Malformed request, now quitting\n"); return -1; }else if(inBuf[1] == STAT_NOS_FILE) { printf("Error: No such file, now quitting\n"); return -1; }else if(inBuf[1] == STAT_NOS_USER) { printf("Error: No such user, now quitting\n"); return -1; }else if(inBuf[1] == STAT_UNK_STAT) { printf("Error: Unknown responce from server, now quitting\n"); return -1; }else if(inBuf[1] == STAT_ERROR) { printf("Error: General error has occured, now quitting\n"); return -1; }else if(inBuf[1] != STAT_OK) { printf("Error: An unknown error has occured %d, now quiting\n",inBuf[1]); return -1; } // Set the packet type int size = 0; buf[0] = CMD_PUT; buf[1] = STAT_OK; size+=2; // Make sure file exists if(fcheck_for_file(fileName) < 0) { printf("Error: bad filename: %s\n",fileName); return -1; } // Open file???? WHY???? f = fopen(fileName, "rb"); if(f == NULL) { printf("Error: Could not open file\n"); return -1; } // Get file size and store it in packet filesize = fsize(fileName); *(int*)(buf+size) = htonl(filesize); size += 4; if(filesize <= 0) { fprintf(stderr,"Error: bad file size, %d", filesize); return -1; } // Send packet with STAT_OK and file size net_send_tcp(n->sock, buf, size); // Recieve a reply from the server inBuf = net_recv_tcp(n->sock); cmd = command_parse(inBuf); // Make sure it is a CMD_GET type if(cmd->type != CMD_PUT) { fprintf(stderr,"Error: Unexpected packet type\n"); return -1; } // Make sure the client status is STAT_OK if(cmd->status != STAT_OK) { fprintf(stderr,"Error: Unexpected packet status, %d\n",cmd->status); return -1; } // Reset buf and size; memset(buf, 0, RCVBUFSIZE); size = 0; // Setup packet header buf[0] = CMD_GET; buf[1] = STAT_MF; size += 2; // Read in and store all the file data filedata = (char *)malloc(filesize); if(fread(filedata, 1, filesize, f) != filesize) { fprintf(stderr,"Error: Could not read all the data in file\n"); return -1; } // Actually send the file!! //TODO: make the blocksize a config file option net_send_fragments_tcp(n->sock, filedata, filesize, 400); return 0; }
void test_parsing(void) { struct external_command *ext_command = NULL; contact *created_contact = NULL; contact *fetched_contact = NULL; const char *cmdstr = "[1234567890] ADD_HOST_COMMENT;my_host;0;15;this is my comment, there are many like it but this one is mine"; registered_commands_init(20); { g_clear_error(&error); ok(NULL == command_parse(cmdstr, COMMAND_SYNTAX_NOKV, &error), "We can't parse commands when none are registered"); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_UNKNOWN_COMMAND), "The error code looks like expected"); ext_command = command_create("ADD_HOST_COMMENT", test__add_host_comment_handler, "This is a description for a command named ADD_HOST_COMMENT", NULL); command_argument_add(ext_command, "host", STRING, NULL, NULL); b_val = 0; command_argument_add(ext_command, "persistent", BOOL, &b_val, NULL); i_val = 42; command_argument_add(ext_command, "author", INTEGER, &i_val, NULL); s_val = "No comment"; command_argument_add(ext_command, "comment", STRING, s_val, NULL); command_register(ext_command, -1); g_clear_error(&error); ext_command = command_parse("[] UNKNOWN_COMMAND", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_MALFORMED_COMMAND), "Malformed command error is raised for malformed commands"); ok(NULL == ext_command, "No command returned for malformed command"); g_clear_error(&error); ext_command = command_parse("[UNKNOWN_COMMAND", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_MALFORMED_COMMAND), "Malformed command error is raised for malformed commands"); ok(NULL == ext_command, "No command returned for malformed command"); g_clear_error(&error); ext_command = command_parse("[139414354] UNKNOWN_COMMAND", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_UNKNOWN_COMMAND), "Unknown command error is raised for unknown commands"); ok(NULL == ext_command, "No command returned for unknown command"); g_clear_error(&error); ext_command = command_parse(cmdstr, COMMAND_SYNTAX_NOKV, &error); ok(error == NULL, "The command parses without error"); ok(!strcmp("my_host", command_argument_get_value(ext_command, "host")), "Host value parsed successfully"); ok(0 == *(int *)command_argument_get_value(ext_command, "persistent"), "Persistent value parsed successfully"); ok(15 == *(int *)command_argument_get_value(ext_command, "author"), "Author value parsed successfully"); ok(!strcmp("this is my comment, there are many like it but this one is mine", command_argument_get_value(ext_command, "comment")), "Comment value parsed successfully"); command_destroy(ext_command); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_HOST_COMMENT;my_host;0;15;this is my newline\n, there are many like it but this one is\n m\ni\nn\ne", COMMAND_SYNTAX_NOKV, &error); ok(error == NULL, "Command containing newlines parses without error"); ok(!strcmp("this is my newline\n, there are many like it but this one is\n m\ni\nn\ne", command_argument_get_value(ext_command, "comment")), "Comment containing newlines parsed successfully"); command_destroy(ext_command); g_clear_error(&error); ext_command = command_parse(cmdstr, COMMAND_SYNTAX_NOKV, &error); ok(0 == command_execute_handler(ext_command), "Callback exit value properly passed on"); ok(!strcmp("my_host", received_host), "Host value passed to callback"); ok(0 == *received_persistent, "Persistent value passed to callback"); ok(received_entry_time == 1234567890, "Entry time passed correctly to callback"); command_destroy(ext_command); free(received_host); free(received_persistent); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_HOST_COMMENT;;1", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_PARSE_MISSING_ARG), "Missing arguments are complained about"); ok(ext_command == NULL, "No command returned for command with missing arguments"); g_clear_error(&error); ext_command = command_parse("[15341345] ADD_HOST_COMMENT", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_PARSE_MISSING_ARG), "Missing arguments are complained about (no arguments supplied)"); ok(ext_command == NULL, "No command returned for command with missing arguments"); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_HOST_COMMENT;my_host;0;441;this is my comment, there are many like it but this one is mine;Post-semi-colon stuff", COMMAND_SYNTAX_NOKV, &error); ok(error == NULL, "Last string argument may contain semi-colons"); ok(ext_command != NULL, "A command should be returned when last string-argument has semi-colons"); command_destroy(ext_command); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_HOST_COMMENT;my_host;0;Dora the Explora';this is my comment, there are many like it but this one is mine", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_PARSE_TYPE_MISMATCH), "Type errors are complained about"); ok(ext_command == NULL, "No command returned for command with argument type errors"); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_HOST_COMMENT;my_host;1;4lyfe;this is my comment, there are many like it but this one is mine", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_PARSE_TYPE_MISMATCH), "Junk characters after integer arguments are complained about"); ok(ext_command == NULL, "No command returned for command with argument type mismatch errors"); g_clear_error(&error); ext_command = command_create("ADD_HOST_COMMENT_WITH_TIMESTAMP", test__add_host_comment_handler, "This is a description for a command named ADD_HOST_COMMENT", NULL); command_argument_add(ext_command, "host", STRING, NULL, NULL); command_argument_add(ext_command, "persistent", BOOL, NULL, NULL); i_val = 42; command_argument_add(ext_command, "author", INTEGER, &i_val, NULL); s_val = "No comment"; command_argument_add(ext_command, "comment", STRING, s_val, NULL); t_val = 0; command_argument_add(ext_command, "timestamp", TIMESTAMP, &t_val, NULL); command_register(ext_command, -1); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_HOST_COMMENT_WITH_TIMESTAMP;my_host;1;441;this is my comment, there are many like it but this one is mine;1234987650", COMMAND_SYNTAX_NOKV, &error); ok(error == NULL, "No error when parsing proper commands"); ok(1234987650 == *(time_t *)command_argument_get_value(ext_command, "timestamp"), "Timestamp value parsed successfully"); command_destroy(ext_command); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_HOST_COMMENT_WITH_TIMESTAMP;my_host;4;441;this is my comment, there are many like it but this one is mine;1234987650", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_VALIDATION_FAILURE), "Invalid BOOL value (4) is complained about"); ok(NULL == ext_command, "No command returned for command with invalid argument values"); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_HOST_COMMENT_WITH_TIMESTAMP;my_host;1;441;this is my comment, there are many like it but this one is mine;14:49", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_PARSE_TYPE_MISMATCH), "Malformed timestamp value is complained about"); ok(NULL == ext_command, "No command returned for command with argument type mismatch"); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_HOST_COMMENT_WITH_TIMESTAMP;my_host;1;441;;", COMMAND_SYNTAX_NOKV, &error); ok(error == NULL, "Missing arguments which have default values are not complained about"); ok(!strcmp("No comment", command_argument_get_value(ext_command, "comment")), "Default value is used for missing argument"); ok(t_val == *(time_t *)command_argument_get_value(ext_command, "timestamp"), "Default value is used for missing argument at end of arg string"); command_destroy(ext_command); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_HOST_COMMENT_WITH_TIMESTAMP;some_host;;441;;13485799", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_PARSE_MISSING_ARG), "Missing arguments which don't have default values are complained about"); ok(NULL == ext_command, "No command returned for command with missing argument and no default"); g_clear_error(&error); ext_command = command_create("ADD_SVC_COMMENT", test__add_service_comment_handler, "This is a description for a command named CMD_ADD_SVC_COMMENT", NULL); command_argument_add(ext_command, "service", SERVICE, NULL, NULL); command_argument_add(ext_command, "persistent", BOOL, &b_val, NULL); command_argument_add(ext_command, "author", INTEGER, &i_val, NULL); command_argument_add(ext_command, "comment", STRING, s_val, NULL); command_register(ext_command, -1); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_SVC_COMMENT;my_host;NO_SUCH_SERVICE;1;441;this is my service comment, there are many like it but this one is mine", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_VALIDATION_FAILURE), "Invalid service is complained about"); ok(NULL == ext_command, "No command returned for command with invalid service"); g_clear_error(&error); ext_command = command_create("ADD_SVC_COMMENT_2", test__add_service_comment_handler, "This is a description for a command with a custom service validator", NULL); command_argument_add(ext_command, "service", SERVICE, NULL, custom_service_validator); command_argument_add(ext_command, "persistent", BOOL, &b_val, NULL); command_argument_add(ext_command, "author", INTEGER, &i_val, NULL); command_argument_add(ext_command, "comment", STRING, s_val, NULL); command_register(ext_command, -1); g_clear_error(&error); ext_command = command_parse("[1234567890] ADD_SVC_COMMENT_2;my_host;LETS_PRETEND_THIS_EXISTS;1;441;this is my service comment, there are many like it but this one is mine", COMMAND_SYNTAX_NOKV, &error); ok(error == NULL, "Custom validator does not decline our invalid service"); command_destroy(ext_command); g_clear_error(&error); ext_command = command_create("DEL_HOST_COMMENT", test__del_host_comment_handler, "This command is used to delete a specific host comment.", NULL); command_argument_add(ext_command, "comment_id", ULONG, NULL, NULL); command_register(ext_command, -1); g_clear_error(&error); ext_command = command_parse("[1234567890] DEL_HOST_COMMENT;10;Excess argument;snurre", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_PARSE_EXCESS_ARG), "Excess arguments are complained about"); ok(ext_command == NULL, "No command returned for commands with excess arguments"); g_clear_error(&error); ext_command = command_parse("[1234567890] DEL_HOST_COMMENT;10", COMMAND_SYNTAX_NOKV, &error); ok((unsigned long) 10 == *(unsigned long *)command_argument_get_value(ext_command, "comment_id"), "ULONG argument parsed correctly"); command_destroy(ext_command); ext_command = command_create("DEL_HOST_COMMENT_2", test__del_host_comment_handler, "This command is used to delete a specific host comment.", "int=comment_id;str=string_arg"); command_register(ext_command, -1); g_clear_error(&error); ext_command = command_parse("[1234567890] DEL_HOST_COMMENT_2;10;foobar", COMMAND_SYNTAX_NOKV, &error); ok(error == NULL, "No error when parsing command created with argspec"); ok(!strcmp("foobar", command_argument_get_value(ext_command, "string_arg")), "Can parse command created with argspec (string arg)"); ok(10 == *(int *)command_argument_get_value(ext_command, "comment_id"), "Can parse command created with argspec (int arg)"); command_destroy(ext_command); g_clear_error(&error); ext_command = command_parse("[1234567890] DEL_HOST_COMMENT_2;1;", COMMAND_SYNTAX_NOKV, &error); ok (ext_command == NULL, "Missing argument at end of arg string is complained about"); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_PARSE_MISSING_ARG), "Missing argument at end of arg string raises the correct error"); g_clear_error(&error); ext_command = command_create("DISABLE_NOTIFICATIONS", test__disable_notifications_handler, "Disables host and service notifications on a program-wide basis.", NULL); command_register(ext_command, -1); ext_command = command_parse("[1234567890] DISABLE_NOTIFICATIONS", COMMAND_SYNTAX_NOKV, &error); ok(ext_command != NULL, "No problem parsing commands with no arguments (when none required)"); command_destroy(ext_command); g_clear_error(&error); ext_command = command_create("DO_THING_WITH_TIMEPERIOD", test__do_thing_with_timeperiod_handler, "Does a thing with a timeperiod", NULL); command_argument_add(ext_command, "timeperiod", TIMEPERIOD, NULL, NULL); command_register(ext_command, -1); g_clear_error(&error); ext_command = command_parse("[1234567890] DO_THING_WITH_TIMEPERIOD;24x8", COMMAND_SYNTAX_NOKV, &error); ok(ext_command == NULL, "No command returned when timeperiod arg is invalid"); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_VALIDATION_FAILURE), "Validation error raised for invalid timeperiod"); registered_timeperiod = find_timeperiod("24x7"); assert(NULL != registered_timeperiod); g_clear_error(&error); ext_command = command_parse("[1234567890] DO_THING_WITH_TIMEPERIOD;24x7", COMMAND_SYNTAX_NOKV, &error); ok(ext_command != NULL, "Command returned when timeperiod arg is not invalid"); ok(error == NULL, "Validation error not raised for valid timeperiod"); ok(registered_timeperiod == command_argument_get_value(ext_command, "timeperiod"), "The correct timeperiod is returned"); command_destroy(ext_command); /** CONTACT SETUP*/ g_clear_error(&error); ext_command = command_create("FIND_CONTACT", test__do_thing_with_contact_handler, "Does a thing with contact", NULL); command_argument_add(ext_command, "contact", CONTACT, NULL, NULL); command_register(ext_command, -1); created_contact = find_contact("nagiosadmin"); assert(NULL != created_contact); /** CONTACT TEST*/ g_clear_error(&error); ext_command = command_parse("[1234567890] FIND_CONTACT;bango", COMMAND_SYNTAX_NOKV, &error); ok(ext_command == NULL, "No command returned when contact arg is invalid"); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_VALIDATION_FAILURE), "Validation error raised for invalid contact"); /** CONTACT TEST*/ g_clear_error(&error); ext_command = command_parse("[1234567890] FIND_CONTACT;nagiosadmin", COMMAND_SYNTAX_NOKV, &error); ok(ext_command != NULL, "Command returned when contact arg is not invalid"); ok(error == NULL, "Validation error not raised for valid contact"); fetched_contact = command_argument_get_value(ext_command, "contact"); ok(created_contact->name == fetched_contact->name, "The correct contact is returned"); /** CONTACT TEARDOWN*/ command_destroy(ext_command); g_clear_error(&error); ext_command = command_parse("[1234567890] _MY_CUSTOMARILY_CUSTOM_CUSTARD_COMMAND;foo;bar;baz;33", COMMAND_SYNTAX_NOKV, &error); ok(g_error_matches(error, NM_COMMAND_ERROR, CMD_ERROR_CUSTOM_COMMAND), "Custom command reported as such"); ok(ext_command != NULL, "Raw command returned when parsing custom command"); ok(!strcmp("foo;bar;baz;33", command_raw_arguments(ext_command)), "Raw arguments properly set for custom command"); ok(command_entry_time(ext_command) == (time_t)1234567890, "Entry time set for custom command"); command_destroy(ext_command); g_clear_error(&error); } registered_commands_deinit(); }