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