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