Fix handling of errors with strtol(), factor out port parsing
[trust_router.git] / tid / example / tidc_main.c
1 /*
2  * Copyright (c) 2012, 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 <gsscon.h>
41 #include <tr_debug.h>
42 #include <tid_internal.h>
43 #include <trust_router/tr_dh.h>
44 #include <trust_router/tid.h>
45 #include <tr_inet_util.h>
46
47 static void tidc_resp_handler (TIDC_INSTANCE * tidc, 
48                         TID_REQ *req,
49                         TID_RESP *resp, 
50                         void *cookie) 
51 {
52   int c_keylen = 0;
53   unsigned char *c_keybuf = NULL;
54   int i;
55   struct timeval tv;
56
57   printf ("Response received! Realm = %s, Community = %s.\n", resp->realm->buf, resp->comm->buf);
58
59   /* Generate the client key -- TBD, handle more than one server */
60   if (TID_SUCCESS != resp->result) {
61     fprintf(stderr, "tidc_resp_handler: Response is an error.\n");
62     return;
63   }
64
65   if (!resp->servers) {
66     fprintf(stderr, "tidc_resp_handler: Response does not contain server info.\n");
67     return;
68   }
69   if (tid_srvr_get_key_expiration(tid_resp_get_server(resp, 0), &tv))
70     printf("Error reading key expiration\n");
71   else
72     printf("Key expiration: %s", ctime(&tv.tv_sec));
73
74
75   if (0 > (c_keylen = tr_compute_dh_key(&c_keybuf, 
76                                       resp->servers->aaa_server_dh->pub_key, 
77                                       req->tidc_dh))) {
78     
79     printf("tidc_resp_handler: Error computing client key.\n");
80     return;
81   }
82   
83   /* Print out the client key. */
84   printf("Client Key Generated (len = %d):\n", c_keylen);
85   for (i = 0; i < c_keylen; i++) {
86     printf("%.2x", c_keybuf[i]); 
87   }
88   printf("\n");
89
90   return;
91 }
92
93
94 static void print_version_info(void)
95 {
96   printf("Moonshot TID Client %s\n\n", PACKAGE_VERSION);
97 }
98
99 /* command-line option setup */
100
101 /* argp global parameters */
102 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
103
104 /* doc strings */
105 static const char doc[]=PACKAGE_NAME " - Moonshot TID Client " PACKAGE_VERSION;
106 static const char arg_doc[]="<server> <RP-realm> <target-realm> <community> [<port>]"; /* string describing arguments, if any */
107
108 /* define the options here. Fields are:
109  * { long-name, short-name, variable name, options, help description } */
110 static const struct argp_option cmdline_options[] = {
111     { "version", 'v', NULL, 0, "Print version information and exit"},
112     { NULL }
113 };
114
115 /* structure for communicating with option parser */
116 struct cmdline_args {
117   char *server;
118   char *rp_realm;
119   char *target_realm;
120   char *community;
121   int port; /* optional */
122 };
123
124 /* parser for individual options - fills in a struct cmdline_args */
125 static error_t parse_option(int key, char *arg, struct argp_state *state)
126 {
127   /* get a shorthand to the command line argument structure, part of state */
128   struct cmdline_args *arguments=state->input;
129
130   switch (key) {
131   case ARGP_KEY_ARG: /* handle argument (not option) */
132     switch (state->arg_num) {
133     case 0:
134       arguments->server=arg;
135       break;
136
137     case 1:
138       arguments->rp_realm=arg;
139       break;
140
141     case 2:
142       arguments->target_realm=arg;
143       break;
144
145     case 3:
146       arguments->community=arg;
147       break;
148
149     case 4:
150       arguments->port=tr_parse_port(arg); /* optional */
151       if (arguments->port < 0) {
152         switch(-(arguments->port)) {
153           case ERANGE:
154             printf("\nError parsing port (%s): port must be an integer in the range 1 - 65535\n\n", arg);
155             break;
156
157           default:
158             printf("\nError parsing port (%s): %s\n\n", arg, strerror(-arguments->port));
159             break;
160         }
161         argp_usage(state);
162       }
163       break;
164
165     default:
166       /* too many arguments */
167       argp_usage(state);
168     }
169     break;
170
171   case ARGP_KEY_END: /* no more arguments */
172     if (state->arg_num < 4) {
173       /* not enough arguments encountered */
174       argp_usage(state);
175     }
176     break;
177
178   case 'v':
179     print_version_info();
180     exit(0);
181
182   default:
183     return ARGP_ERR_UNKNOWN;
184   }
185
186   return 0; /* success */
187 }
188
189 /* assemble the argp parser */
190 static struct argp argp = {cmdline_options, parse_option, arg_doc, doc};
191
192 int main (int argc, 
193           char *argv[]) 
194 {
195   TIDC_INSTANCE *tidc;
196   int conn = 0;
197   int rc;
198   gss_ctx_id_t gssctx;
199   struct cmdline_args opts;
200
201   /* parse the command line*/
202   /* set defaults */
203   opts.server=NULL;
204   opts.rp_realm=NULL;
205   opts.target_realm=NULL;
206   opts.community=NULL;
207   opts.port=TID_PORT;
208
209   argp_parse(&argp, argc, argv, 0, 0, &opts);
210   /* TBD -- validity checking, dealing with quotes, etc. */
211
212   print_version_info();
213
214   /* Use standalone logging */
215   tr_log_open();
216
217   /* set logging levels */
218   talloc_set_log_stderr();
219   tr_log_threshold(LOG_CRIT);
220   tr_console_threshold(LOG_DEBUG);
221
222   printf("TIDC Client:\nServer = %s, rp_realm = %s, target_realm = %s, community = %s, port = %i\n", opts.server, opts.rp_realm, opts.target_realm, opts.community, opts.port);
223  
224   /* Create a TID client instance & the client DH */
225   tidc = tidc_create();
226   tidc_set_dh(tidc, tr_create_dh_params(NULL, 0));
227   if (tidc_get_dh(tidc) == NULL) {
228     printf("Error creating client DH params.\n");
229     return 1;
230   }
231
232   /* Set-up TID connection */
233   if (-1 == (conn = tidc_open_connection(tidc, opts.server, opts.port, &gssctx))) {
234     /* Handle error */
235     printf("Error in tidc_open_connection.\n");
236     return 1;
237   };
238
239   /* Send a TID request */
240   if (0 > (rc = tidc_send_request(tidc, conn, gssctx, opts.rp_realm, opts.target_realm, opts.community, 
241                                   &tidc_resp_handler, NULL))) {
242     /* Handle error */
243     printf("Error in tidc_send_request, rc = %d.\n", rc);
244     return 1;
245   }
246     
247   /* Clean-up the TID client instance, and exit */
248   tidc_destroy(tidc);
249
250   return 0;
251 }
252