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