Fix handling of errors with strtol(), factor out port parsing
[trust_router.git] / tr / trmon_main.c
1 /*
2  * Copyright (c) 2012-2018, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <talloc.h>
38 #include <argp.h>
39
40 #include <mon_internal.h>
41 #include <tr_debug.h>
42 #include <tr_inet_util.h>
43
44
45 /* command-line option setup */
46 static void print_version_info(void)
47 {
48   printf("Moonshot Trust Router Monitoring Client %s\n\n", PACKAGE_VERSION);
49 }
50
51
52 /* argp global parameters */
53 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
54
55 /* doc strings */
56 static const char doc[]=PACKAGE_NAME " - Moonshot Trust Router Monitoring Client";
57 static const char arg_doc[]="<server> <port> <command> [<option> ...]"; /* string describing arguments, if any */
58
59 /* define the options here. Fields are:
60  * { long-name, short-name, variable name, options, help description } */
61 static const struct argp_option cmdline_options[] = {
62     { "version", 'v', NULL, 0, "Print version information and exit" },
63     {NULL}
64 };
65
66 #define MAX_OPTIONS 20
67 /* structure for communicating with option parser */
68 struct cmdline_args {
69   char *server;
70   int port;
71   MON_CMD command;
72   MON_OPT_TYPE options[MAX_OPTIONS];
73   unsigned int n_options;
74 };
75
76 /* parser for individual options - fills in a struct cmdline_args */
77 static error_t parse_option(int key, char *arg, struct argp_state *state)
78 {
79   int err = 0;
80
81   /* get a shorthand to the command line argument structure, part of state */
82   struct cmdline_args *arguments=state->input;
83
84   switch (key) {
85     case 'v':
86       print_version_info();
87       exit(0);
88
89     case ARGP_KEY_ARG: /* handle argument (not option) */
90       switch (state->arg_num) {
91         case 0:
92           arguments->server = arg;
93           break;
94
95         case 1:
96           arguments->port=tr_parse_port(arg); /* optional */
97           if (arguments->port < 0) {
98             switch(-(arguments->port)) {
99               case ERANGE:
100                 printf("\nError parsing port (%s): port must be an integer in the range 1 - 65535\n\n", arg);
101                 break;
102
103               default:
104                 printf("\nError parsing port (%s): %s\n\n", arg, strerror(-arguments->port));
105                 break;
106             }
107             argp_usage(state);
108           }
109           break;
110
111         case 2:
112           arguments->command=mon_cmd_from_string(arg);
113           if (arguments->command == MON_CMD_UNKNOWN) {
114             printf("\nUnknown command '%s'\n\n", arg);
115             err = 1;
116           }
117           break;
118
119         default:
120           if (arguments->n_options >= MAX_OPTIONS) {
121             printf("\nToo many command options given, limit is %d\n\n", MAX_OPTIONS);
122             err = 1;
123             break;
124           }
125
126           arguments->options[arguments->n_options] = mon_opt_type_from_string(arg);
127           if (arguments->options[arguments->n_options] == OPT_TYPE_UNKNOWN) {
128             printf("\nUnknown command option '%s'\n\n", arg);
129             err = 1;
130           }
131           arguments->n_options++;
132           break;
133       }
134       break;
135
136     case ARGP_KEY_END: /* no more arguments */
137       if (state->arg_num < 3) {
138         /* not enough arguments encountered */
139         err = 1;
140       }
141       break;
142
143     default:
144       return ARGP_ERR_UNKNOWN;
145   }
146
147   if (err) {
148     argp_usage(state);
149     return EINVAL; /* argp_usage() usually does not return, but just in case */
150   }
151
152   return 0; /* success */
153 }
154
155
156 /* assemble the argp parser */
157 static struct argp argp = {cmdline_options, parse_option, arg_doc, doc};
158
159 int main(int argc, char *argv[])
160 {
161   TALLOC_CTX *main_ctx=talloc_new(NULL);
162   MONC_INSTANCE *monc = NULL;
163   MON_REQ *req = NULL;
164   MON_RESP *resp = NULL;
165   unsigned int ii;
166
167   struct cmdline_args opts;
168   int retval=1; /* exit with an error status unless this gets set to zero */
169
170   /* parse the command line*/
171   /* set defaults */
172   opts.server = NULL;
173   opts.port = TRP_PORT;
174   opts.command = MON_CMD_UNKNOWN;
175   opts.n_options = 0;
176
177   argp_parse(&argp, argc, argv, 0, 0, &opts);
178
179   /* Use standalone logging */
180   tr_log_open();
181
182   /* set logging levels */
183   talloc_set_log_stderr();
184   tr_log_threshold(LOG_CRIT);
185   tr_console_threshold(LOG_WARNING);
186
187   /* Create a MON client instance */
188   monc = monc_new(main_ctx);
189   if (monc == NULL) {
190     printf("Error allocating client instance.\n");
191     goto cleanup;
192   }
193
194   /* Set-up MON connection */
195   if (0 != monc_open_connection(monc, opts.server, opts.port)) {
196     /* Handle error */
197     printf("Error opening connection to %s:%d.\n", opts.server, opts.port);
198     goto cleanup;
199   };
200
201   req = mon_req_new(main_ctx, opts.command);
202   for (ii=0; ii < opts.n_options; ii++) {
203     if (MON_SUCCESS != mon_req_add_option(req, opts.options[ii])) {
204       printf("Error adding option '%s' to request. Request not sent.\n",
205              mon_opt_type_to_string(opts.options[ii]));
206       goto cleanup;
207     }
208
209   }
210
211   /* Send a MON request and get the response */
212   resp = monc_send_request(main_ctx, monc, req);
213
214   if (resp == NULL) {
215     /* Handle error */
216     printf("Error executing monitoring request.\n");
217     goto cleanup;
218   }
219
220   /* Print the JSON to stdout */
221   json_dumpf(mon_resp_encode(resp), stdout, JSON_INDENT(4));
222   printf("\n");
223
224   /* success */
225   retval = 0;
226
227   /* Clean-up the MON client instance, and exit */
228 cleanup:
229   talloc_free(main_ctx);
230   return retval;
231 }
232