tids: build after gsscon change.
[trust_router.git] / tid / tids.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 <assert.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <string.h>
39 #include <stdio.h>
40 #include <errno.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <jansson.h>
44
45 #include <trust_router/tid.h>
46 #include <gsscon.h>
47 #include <tr_msg.h>
48
49 static TID_RESP *tids_create_response (TIDS_INSTANCE *tids, TID_REQ *req) 
50 {
51   TID_RESP *resp;
52
53   if ((NULL == (resp = calloc(sizeof(TID_RESP), 1)))) {
54     fprintf(stderr, "tids_create_response: Error allocating response structure.\n");
55     return NULL;
56   }
57   
58   resp->result = TID_SUCCESS; /* presume success */
59   if ((NULL == (resp->rp_realm = tr_dup_name(req->rp_realm))) ||
60       (NULL == (resp->realm = tr_dup_name(req->realm))) ||
61       (NULL == (resp->comm = tr_dup_name(req->comm)))) {
62     fprintf(stderr, "tids_create_response: Error allocating fields in response.\n");
63     return NULL;
64   }
65   if (req->orig_coi) {
66     if (NULL == (resp->orig_coi = tr_dup_name(req->orig_coi))) {
67       fprintf(stderr, "tids_create_response: Error allocating fields in response.\n");
68       return NULL;
69     }
70   }
71   return resp;
72 }
73
74 static void tids_destroy_response(TIDS_INSTANCE *tids, TID_RESP *resp) 
75 {
76   if (resp) {
77     if (resp->err_msg)
78       tr_free_name(resp->err_msg);
79     if (resp->rp_realm)
80       tr_free_name(resp->rp_realm);
81     if (resp->realm)
82       tr_free_name(resp->realm);
83     if (resp->comm)
84       tr_free_name(resp->comm);
85     if (resp->orig_coi)
86       tr_free_name(resp->orig_coi);
87     free (resp);
88   }
89 }
90
91 static int tids_listen (TIDS_INSTANCE *tids, int port) 
92 {
93     int rc = 0;
94     int conn = -1;
95     int optval = 1;
96
97     union {
98       struct sockaddr_storage storage;
99       struct sockaddr_in in4;
100     } addr;
101
102     struct sockaddr_in *saddr = (struct sockaddr_in *) &addr.in4;
103     
104     saddr->sin_port = htons (port);
105     saddr->sin_family = AF_INET;
106     saddr->sin_addr.s_addr = INADDR_ANY;
107
108     if (0 > (conn = socket (AF_INET, SOCK_STREAM, 0)))
109       return conn;
110         
111     setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
112
113     if (0 > (rc = bind (conn, (struct sockaddr *) saddr, sizeof(struct sockaddr_in))))
114       return rc;
115         
116     if (0 > (rc = listen(conn, 512)))
117       return rc;
118     
119     fprintf (stdout, "tids_listen: TID Server listening on port %d\n", port);
120     return conn; 
121 }
122
123 static int tids_auth_cb(gss_name_t clientName, gss_buffer_t displayName,
124                         void *data)
125 {
126   assert(data == NULL);
127   assert (clientName != NULL);
128   assert(displayName->value != NULL);
129   return 0;
130 }
131
132 static int tids_auth_connection (int conn, gss_ctx_id_t *gssctx)
133 {
134   int rc = 0;
135   int auth, autherr = 0;
136
137   if (rc = gsscon_passive_authenticate(conn, gssctx, tids_auth_cb, NULL)) {
138     fprintf(stderr, "tids_auth_connection: Error from gsscon_passive_authenticate(), rc = %d.\n", rc);
139     return -1;
140   }
141
142   if (rc = gsscon_authorize(*gssctx, &auth, &autherr)) {
143     fprintf(stderr, "tids_auth_connection: Error from gsscon_authorize, rc = %d, autherr = %d.\n", 
144             rc, autherr);
145     return -1;
146   }
147
148   if (auth)
149     fprintf(stdout, "tids_auth_connection: Connection authenticated, conn = %d.\n", conn);
150   else
151     fprintf(stderr, "tids_auth_connection: Authentication failed, conn %d.\n", conn);
152
153   return !auth;
154 }
155
156 static int tids_read_request (TIDS_INSTANCE *tids, int conn, gss_ctx_id_t *gssctx, TR_MSG **mreq)
157 {
158   int err;
159   char *buf;
160   size_t buflen = 0;
161
162   if (err = gsscon_read_encrypted_token(conn, *gssctx, &buf, &buflen)) {
163     if (buf)
164       free(buf);
165     return -1;
166   }
167
168   fprintf(stdout, "tids_read_request():Request Received, %u bytes.\n", (unsigned) buflen);
169
170   /* Parse request */
171   if (NULL == ((*mreq) = tr_msg_decode(buf, buflen))) {
172     fprintf(stderr, "tids_read_request():Error decoding request.\n");
173     free (buf);
174     return -1;
175   }
176
177   /* If this isn't a TID Request, just drop it. */
178   if (TID_REQUEST != (*mreq)->msg_type) {
179     fprintf(stderr, "tids_read_request(): Not a TID Request, dropped.\n");
180     return -1;
181   }
182
183   free (buf);
184   return buflen;
185 }
186
187 static int tids_handle_request (TIDS_INSTANCE *tids, TR_MSG *mreq, TID_RESP **resp) 
188 {
189   int rc;
190
191   /* Check that this is a valid TID Request.  If not, send an error return. */
192   if ((!mreq->tid_req) ||
193       (!mreq->tid_req->rp_realm) ||
194       (!mreq->tid_req->realm) ||
195       (!mreq->tid_req->comm)) {
196     fprintf(stderr, "tids_handle_request():Not a valid TID Request.\n");
197     (*resp)->result = TID_ERROR;
198     (*resp)->err_msg = tr_new_name("Bad request format");
199     return -1;
200   }
201
202   /* Call the caller's request handler */
203   /* TBD -- Handle different error returns/msgs */
204   if (0 > (rc = (*tids->req_handler)(tids, mreq->tid_req, &(*resp), tids->cookie))) {
205     /* set-up an error response */
206     (*resp)->result = TID_ERROR;
207     if (!(*resp)->err_msg)      /* Use msg set by handler, if any */
208       (*resp)->err_msg = tr_new_name("Internal processing error");
209   }
210   else {
211     /* set-up a success response */
212     (*resp)->result = TID_SUCCESS;
213     (*resp)->err_msg = NULL;    /* No error msg on successful return */
214   }
215     
216   return rc;
217 }
218
219 int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg) {
220   TID_RESP *resp = NULL;
221   int rc = 0;
222
223   /* If we already sent a response, don't send another no matter what. */
224   if (req->resp_sent)
225     return 0;
226
227   if (NULL == (resp = tids_create_response(tids, req))) {
228     fprintf(stderr, "tids_send_err_response: Can't create response.\n");
229     return -1;
230   }
231
232   /* mark this as an error response, and include the error message */
233   resp->result = TID_ERROR;
234   resp->err_msg = tr_new_name((char *)err_msg);
235
236   rc = tids_send_response(tids, req, resp);
237   
238   tids_destroy_response(tids, resp);
239   return rc;
240 }
241
242 int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
243 {
244   int err;
245   TR_MSG mresp;
246   char *resp_buf;
247
248   if ((!tids) || (!req) || (!resp))
249     fprintf (stderr, "tids_send_response: Invalid parameters.\n");
250
251   /* Never send a second response if we already sent one. */
252   if (req->resp_sent)
253     return 0;
254
255   mresp.msg_type = TID_RESPONSE;
256   mresp.tid_resp = resp;
257   
258   if (NULL == (resp_buf = tr_msg_encode(&mresp))) {
259     fprintf(stderr, "tids_send_response: Error encoding json response.\n");
260     return -1;
261   }
262
263   fprintf(stderr, "tids_send_response: Encoded response:\n%s\n", resp_buf);
264   
265   /* Send the response over the connection */
266   if (err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf, 
267                                           strlen(resp_buf) + 1)) {
268     fprintf(stderr, "tids_send_response: Error sending response over connection.\n");
269     return -1;
270   }
271
272   /* indicate that a response has been sent for this request */
273   req->resp_sent = 1;
274
275   free(resp_buf);
276
277   return 0;
278 }
279
280 static void tids_handle_connection (TIDS_INSTANCE *tids, int conn)
281 {
282   TR_MSG *mreq = NULL;
283   TID_RESP *resp = NULL;
284   int rc = 0;
285   gss_ctx_id_t gssctx = GSS_C_NO_CONTEXT;
286
287   if (tids_auth_connection(conn, &gssctx)) {
288     fprintf(stderr, "tids_handle_connection: Error authorizing TID Server connection.\n");
289     close(conn);
290     return;
291   }
292
293   fprintf(stdout, "tids_handle_connection: Connection authorized!\n");
294
295   while (1) {   /* continue until an error breaks us out */
296
297     if (0 > (rc = tids_read_request(tids, conn, &gssctx, &mreq))) {
298       fprintf(stderr, "tids_handle_connection: Error from tids_read_request(), rc = %d.\n", rc);
299       return;
300     } else if (0 == rc) {
301       continue;
302     }
303
304     /* Put connection information into the request structure */
305     mreq->tid_req->conn = conn;
306     mreq->tid_req->gssctx = gssctx;
307
308     /* Allocate a response structure and populate common fields */
309     if (NULL == (resp = tids_create_response (tids, mreq->tid_req))) {
310       fprintf(stderr, "tids_handle_connection: Error creating response structure.\n");
311       /* try to send an error */
312       tids_send_err_response(tids, mreq->tid_req, "Error creating response.\n");
313       return;
314     }
315
316     if (0 > (rc = tids_handle_request(tids, mreq, &resp))) {
317       fprintf(stderr, "tids_handle_connection: Error from tids_handle_request(), rc = %d.\n", rc);
318       /* Fall through, to send the response, either way */
319     }
320
321     if (0 > (rc = tids_send_response(tids, mreq->tid_req, resp))) {
322       fprintf(stderr, "tids_handle_connection: Error from tids_send_response(), rc = %d.\n", rc);
323       /* if we didn't already send a response, try to send a generic error. */
324       if (!mreq->tid_req->resp_sent)
325         tids_send_err_response(tids, mreq->tid_req, "Error sending response.\n");
326       /* Fall through to free the response, either way. */
327     }
328     
329     tids_destroy_response(tids, resp);
330     return;
331   } 
332 }
333
334 TIDS_INSTANCE *tids_create (void)
335 {
336   TIDS_INSTANCE *tids = NULL;
337   if (tids = malloc(sizeof(TIDS_INSTANCE)))
338     memset(tids, 0, sizeof(TIDS_INSTANCE));
339   return tids;
340 }
341
342 int tids_start (TIDS_INSTANCE *tids, 
343                 TIDS_REQ_FUNC *req_handler,
344                 void *cookie)
345 {
346   int listen = -1;
347   int conn = -1;
348   pid_t pid;
349
350   if (0 > (listen = tids_listen(tids, TID_PORT)))
351     perror ("Error from tids_listen()");
352
353   /* store the caller's request handler & cookie */
354   tids->req_handler = req_handler;
355   tids->cookie = cookie;
356
357   while(1) {    /* accept incoming conns until we are stopped */
358
359     if (0 > (conn = accept(listen, NULL, NULL))) {
360       perror("Error from TIDS Server accept()");
361       return 1;
362     }
363
364     if (0 > (pid = fork())) {
365       perror("Error on fork()");
366       return 1;
367     }
368
369     if (pid == 0) {
370       close(listen);
371       tids_handle_connection(tids, conn);
372       close(conn);
373       exit(0);
374     } else {
375       close(conn);
376     }
377   }
378
379   return 1;     /* should never get here */
380 }
381
382 void tids_destroy (TIDS_INSTANCE *tids)
383 {
384   if (tids)
385     free(tids);
386 }
387
388