/** * A program to execute automation when a socket is unreachable * Copyright (C) 2022 Aaron Ball * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include "net.h" #include "runconfig.h" void usage() { fputs( "Usage:\n" " react-tcp-down --ip --port --cmd \n\n" "Arguments:\n" " -i,--ip IP Address to check for port availability\n" " -p,--port Port to check\n" " -c,--cmd Command to run if port is down\n" " -h,--help Print this help text\n" , stderr); } int parse_args(struct runconfig* cfg, int argc, char* argv[]) { int i = 0; int status = 0; while(i < argc) { if(strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) { usage(); return 1; } else if(strcmp(argv[i], "--ip") == 0 || strcmp(argv[i], "-i") == 0) { i++; strcpy(cfg->ip, argv[i]); } else if(strcmp(argv[i], "--port") == 0 || strcmp(argv[i], "-p") == 0) { i++; cfg->port = strtol(argv[i], NULL, 10); } else if(strcmp(argv[i], "--cmd") == 0 || strcmp(argv[i], "-c") == 0) { i++; strncpy(cfg->cmd, argv[i], RUNCONFIG_CMD_MAX); cfg->cmd[RUNCONFIG_CMD_MAX - 1] = '\0'; } i++; } if(cfg->ip[0] == '\0') { fputs("Host IP address required (--ip, -i)\n", stderr); status = -1; } else if(cfg->port <= 0 || cfg->port > 65535) { fputs("Valid port required (--port, -p)\n", stderr); status = -1; } else if(cfg->cmd[0] == '\0') { fputs("Command to execute on port down required (--cmd,-c)\n", stderr); status = -1; } return status; } int main(int argc, char* argv[]) { struct runconfig cfg; runconfig_init(&cfg); if(parse_args(&cfg, argc, argv) != 0) return 1; if(net_tcp_is_up(cfg.ip, cfg.port) == -1) system(cfg.cmd); return 0; }