Merge branch 'master' of moonshot.suchdamage.org:/srv/git/trust_router
[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 int tids_listen (TIDS_INSTANCE *tids, int port) 
49 {
50     int rc = 0;
51     int conn = -1;
52     union {
53       struct sockaddr_storage storage;
54       struct sockaddr_in in4;
55     } addr;
56     struct sockaddr_in *saddr = (struct sockaddr_in *) &addr.in4;
57     
58     saddr->sin_port = htons (port);
59     saddr->sin_family = AF_INET;
60     saddr->sin_addr.s_addr = INADDR_ANY;
61
62     if (0 > (conn = socket (AF_INET, SOCK_STREAM, 0)))
63       return conn;
64         
65     if (0 > (rc = bind (conn, (struct sockaddr *) saddr, sizeof(struct sockaddr_in))))
66       return rc;
67         
68     if (0 > (rc = listen(conn, 512)))
69       return rc;
70     
71     fprintf (stdout, "TID Server listening on port %d\n", port);
72     return conn; 
73 }
74
75 static int tids_auth_connection (int conn, gss_ctx_id_t *gssctx)
76 {
77   int rc = 0;
78   int auth, autherr = 0;
79
80   if (rc = gsscon_passive_authenticate(conn, gssctx)) {
81     fprintf(stderr, "Error from gsscon_passive_authenticate(), rc = %d.\n", rc);
82     return -1;
83   }
84
85   if (rc = gsscon_authorize(*gssctx, &auth, &autherr)) {
86     fprintf(stderr, "Error from gsscon_authorize, rc = %d, autherr = %d.\n", 
87             rc, autherr);
88     return -1;
89   }
90
91   if (auth)
92     fprintf(stdout, "Connection authenticated, conn = %d.\n", conn);
93   else
94     fprintf(stderr, "Authentication failed, conn %d.\n", conn);
95
96   return !auth;
97 }
98
99 static int tids_read_request (TIDS_INSTANCE *tids, int conn, gss_ctx_id_t *gssctx, TR_MSG **mreq)
100 {
101   int err;
102   char *buf;
103   size_t buflen = 0;
104
105   if (err = gsscon_read_encrypted_token(conn, *gssctx, &buf, &buflen)) {
106     if (buf)
107       free(buf);
108     return -1;
109   }
110
111   fprintf(stdout, "tids_read_request():Request Received, %u bytes.\n", (unsigned) buflen);
112
113   /* Parse request */
114   if (NULL == ((*mreq) = tr_msg_decode(buf, buflen))) {
115     printf("tids_read_request():Error decoding request.\n");
116     free (buf);
117     return -1;
118   }
119
120   /* If this isn't a TID Request, just drop it. */
121   if (TID_REQUEST != (*mreq)->msg_type) {
122     printf("tids_read_request(): Not a TID Request, dropped.\n");
123     return -1;
124   }
125
126   free (buf);
127   return buflen;
128 }
129
130 static int tids_handle_request (TIDS_INSTANCE *tids, TR_MSG *mreq, TID_RESP **resp) 
131 {
132   int rc;
133
134   /* Check that this is a valid TID Request.  If not, send an error return. */
135   if ((!mreq->tid_req) ||
136       (!mreq->tid_req->rp_realm) ||
137       (!mreq->tid_req->realm) ||
138       (!mreq->tid_req->comm)) {
139     printf("tids_handle_request():Not a valid TID Request.\n");
140     (*resp)->result = TID_ERROR;
141     (*resp)->err_msg = tr_new_name("Bad request format");
142     return -1;
143   }
144
145   /* Call the caller's request handler */
146   /* TBD -- Handle different error returns/msgs */
147   if (0 > (rc = (*tids->req_handler)(tids, mreq->tid_req, &(*resp), tids->cookie))) {
148     /* set-up an error response */
149     (*resp)->result = TID_ERROR;
150     if (!(*resp)->err_msg)      /* Use msg set by handler, if any */
151       (*resp)->err_msg = tr_new_name("Internal processing error");
152   }
153   else {
154     /* set-up a success response */
155     (*resp)->result = TID_SUCCESS;
156     (*resp)->err_msg = NULL;    /* No msg on successful return */
157   }
158     
159   return rc;
160 }
161
162 int tids_send_response (TIDS_INSTANCE *tids, int conn, gss_ctx_id_t *gssctx, TID_RESP *resp)
163 {
164   int err;
165   TR_MSG mresp;
166   char *resp_buf;
167
168   mresp.msg_type = TID_RESPONSE;
169   mresp.tid_resp = resp;
170   
171   if (NULL == (resp_buf = tr_msg_encode(&mresp))) {
172     fprintf(stderr, "Error decoding json response.\n");
173     return -1;
174   }
175
176   printf("Encoded response:\n%s\n", resp_buf);
177   
178   /* Send the response over the connection */
179   if (err = gsscon_write_encrypted_token (conn, *gssctx, resp_buf, 
180                                           strlen(resp_buf) + 1)) {
181     fprintf(stderr, "Error sending response over connection.\n");
182     return -1;
183   }
184
185   free(resp_buf);
186
187   return 0;
188 }
189
190 static void tids_handle_connection (TIDS_INSTANCE *tids, int conn)
191 {
192   TR_MSG *mreq = NULL;
193   TID_RESP *resp = NULL;
194   int rc = 0;
195   gss_ctx_id_t gssctx = GSS_C_NO_CONTEXT;
196
197   if (tids_auth_connection(conn, &gssctx)) {
198     fprintf(stderr, "Error authorizing TID Server connection.\n");
199     close(conn);
200     return;
201   }
202
203   printf("Connection authorized!\n");
204
205   while (1) {   /* continue until an error breaks us out */
206
207     if (0 > (rc = tids_read_request(tids, conn, &gssctx, &mreq))) {
208       fprintf(stderr, "Error from tids_read_request(), rc = %d.\n", rc);
209       return;
210     } else if (0 == rc) {
211       continue;
212     }
213
214     /* Put connection information into the request structure */
215     mreq->tid_req->conn = conn;
216     mreq->tid_req->gssctx = gssctx;
217
218     /* Allocate a response structure and populate common fields */
219     if ((NULL == (resp = calloc(sizeof(TID_RESP), 1)))) {
220       fprintf(stderr, "Error allocating response structure.\n");
221       return;
222     }
223
224     /* TBD -- handle errors */
225     resp->result = TID_SUCCESS; /* presume success */
226     resp->rp_realm = tr_dup_name(mreq->tid_req->rp_realm);
227     resp->realm = tr_dup_name(mreq->tid_req->realm);
228     resp->comm = tr_dup_name(mreq->tid_req->comm);
229     if (mreq->tid_req->orig_coi)
230       resp->orig_coi = tr_dup_name(mreq->tid_req->orig_coi);
231
232     if (0 > (rc = tids_handle_request(tids, mreq, &resp))) {
233       fprintf(stderr, "Error from tids_handle_request(), rc = %d.\n", rc);
234       return;
235     }
236
237     if (0 > (rc = tids_send_response(tids, conn, &gssctx, resp))) {
238       fprintf(stderr, "Error from tids_send_response(), rc = %d.\n", rc);
239       return;
240     }
241   }  
242
243   return;
244 }
245
246 TIDS_INSTANCE *tids_create (void)
247 {
248   TIDS_INSTANCE *tids = NULL;
249   if (tids = malloc(sizeof(TIDS_INSTANCE)))
250     memset(tids, 0, sizeof(TIDS_INSTANCE));
251   return tids;
252 }
253
254 int tids_start (TIDS_INSTANCE *tids, 
255                 TIDS_REQ_FUNC *req_handler,
256                 void *cookie)
257 {
258   int listen = -1;
259   int conn = -1;
260   pid_t pid;
261   int optval = 1;
262
263   if (0 > (listen = tids_listen(tids, TID_PORT)))
264     perror ("Error from tids_listen()");
265
266   setsockopt(listen, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
267
268   /* store the caller's request handler & cookie */
269   tids->req_handler = req_handler;
270   tids->cookie = cookie;
271
272   while(1) {    /* accept incoming conns until we are stopped */
273
274     if (0 > (conn = accept(listen, NULL, NULL))) {
275       perror("Error from TIDS Server accept()");
276       return 1;
277     }
278
279     if (0 > (pid = fork())) {
280       perror("Error on fork()");
281       return 1;
282     }
283
284     if (pid == 0) {
285       close(listen);
286       tids_handle_connection(tids, conn);
287       close(conn);
288       exit(0);
289     } else {
290       close(conn);
291     }
292   }
293
294   return 1;     /* should never get here */
295 }
296
297 void tids_destroy (TIDS_INSTANCE *tids)
298 {
299   free(tids);
300 }
301
302