summaryrefslogtreecommitdiff
path: root/src/main.c
blob: 3a9245d2d25c3fdbff726e495c078ec3020cd0ac (plain)
    1 /**
    2  * A program to execute automation when a socket is unreachable
    3  * Copyright (C) 2022  Aaron Ball <nullspoon@oper.io>
    4  *
    5  * This program is free software: you can redistribute it and/or modify
    6  * it under the terms of the GNU General Public License as published by
    7  * the Free Software Foundation, either version 3 of the License, or
    8  * (at your option) any later version.
    9  *
   10  * This program is distributed in the hope that it will be useful,
   11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
   12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   13  * GNU General Public License for more details.
   14  *
   15  * You should have received a copy of the GNU General Public License
   16  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
   17  */
   18 #include <stdio.h>
   19 #include <string.h>
   20 
   21 #include "net.h"
   22 #include "runconfig.h"
   23 
   24 void usage() {
   25   fputs("Usage:\n  react-tcp-down <host_ip> <port> <command>\n\n", stderr);
   26 }
   27 
   28 int parse_args(struct runconfig* cfg, int argc, char* argv[]) {
   29   int i = 0;
   30   int status = 0;
   31   while(i < argc) {
   32     if(strcmp(argv[i], "--ip") == 0 || strcmp(argv[i], "-i") == 0) {
   33       i++;
   34       strcpy(cfg->ip, argv[i]);
   35 
   36     } else if(strcmp(argv[i], "--port") == 0 || strcmp(argv[i], "-p") == 0) {
   37       i++;
   38       cfg->port = strtol(argv[i], NULL, 10);
   39 
   40     } else if(strcmp(argv[i], "--cmd") == 0 || strcmp(argv[i], "-c") == 0) {
   41       i++;
   42       strncpy(cfg->cmd, argv[i], RUNCONFIG_CMD_MAX);
   43       cfg->cmd[RUNCONFIG_CMD_MAX - 1] = '\0';
   44     }
   45     i++;
   46   }
   47 
   48   if(cfg->ip[0] == '\0') {
   49     fputs("Host IP address required (--ip, -i)\n", stderr);
   50     status = -1;
   51   } else if(cfg->port <= 0 || cfg->port > 65535) {
   52     fputs("Valid port required (--port, -p)\n", stderr);
   53     status = -1;
   54   } else if(cfg->cmd[0] == '\0') {
   55     fputs("Command to execute on port down required (--cmd,-c)\n", stderr);
   56     status = -1;
   57   }
   58 
   59   return status;
   60 }
   61 
   62 int main(int argc, char* argv[]) {
   63   struct runconfig cfg;
   64 
   65   runconfig_init(&cfg);
   66   if(parse_args(&cfg, argc, argv) != 0)
   67     return 1;
   68 
   69   if(net_tcp_is_up(cfg.ip, cfg.port) == -1)
   70     system(cfg.cmd);
   71   return 0;
   72 }

Generated by cgit