Further cleanup of tr_gss and usage for tids handling
[trust_router.git] / tid / tids.c
1 /*
2  * Copyright (c) 2012, 2015, 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 <fcntl.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 <netdb.h>
44 #include <jansson.h>
45 #include <talloc.h>
46 #include <poll.h>
47 #include <tid_internal.h>
48 #include <gsscon.h>
49 #include <tr_debug.h>
50 #include <tr_msg.h>
51 #include <tr_socket.h>
52 #include <tr_gss.h>
53 #include <tr_event.h>
54
55 static TID_RESP *tids_create_response(TALLOC_CTX *mem_ctx, TIDS_INSTANCE *tids, TID_REQ *req)
56 {
57   TID_RESP *resp=NULL;
58   int success=0;
59
60   if (NULL == (resp = tid_resp_new(mem_ctx))) {
61     tr_crit("tids_create_response: Error allocating response structure.");
62     return NULL;
63   }
64   
65   resp->result = TID_SUCCESS; /* presume success */
66   if ((NULL == (resp->rp_realm = tr_dup_name(req->rp_realm))) ||
67       (NULL == (resp->realm = tr_dup_name(req->realm))) ||
68       (NULL == (resp->comm = tr_dup_name(req->comm)))) {
69     tr_crit("tids_create_response: Error allocating fields in response.");
70     goto cleanup;
71   }
72   if (req->orig_coi) {
73     if (NULL == (resp->orig_coi = tr_dup_name(req->orig_coi))) {
74       tr_crit("tids_create_response: Error allocating fields in response.");
75       goto cleanup;
76     }
77   }
78
79   success=1;
80
81 cleanup:
82   if ((!success) && (resp!=NULL)) {
83     talloc_free(resp);
84     resp=NULL;
85   }
86   return resp;
87 }
88
89 static int tids_handle_request(TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
90 {
91   int rc=-1;
92
93   /* Check that this is a valid TID Request.  If not, send an error return. */
94   if ((!req) ||
95       (!(req->rp_realm)) ||
96       (!(req->realm)) ||
97       (!(req->comm))) {
98     tr_notice("tids_handle_request(): Not a valid TID Request.");
99     resp->result = TID_ERROR;
100     resp->err_msg = tr_new_name("Bad request format");
101     return -1;
102   }
103
104   tr_debug("tids_handle_request: adding self to req path.");
105   tid_req_add_path(req, tids->hostname, tids->tids_port);
106   
107   /* Call the caller's request handler */
108   /* TBD -- Handle different error returns/msgs */
109   if (0 > (rc = (*tids->req_handler)(tids, req, resp, tids->cookie))) {
110     /* set-up an error response */
111     tr_debug("tids_handle_request: req_handler returned error.");
112     resp->result = TID_ERROR;
113     if (!resp->err_msg) /* Use msg set by handler, if any */
114       resp->err_msg = tr_new_name("Internal processing error");
115   }
116   else {
117     /* set-up a success response */
118     tr_debug("tids_handle_request: req_handler returned success.");
119     resp->result = TID_SUCCESS;
120     resp->err_msg = NULL;       /* No error msg on successful return */
121   }
122     
123   return rc;
124 }
125
126 /**
127  * Produces a JSON-encoded msg containing the TID response
128  *
129  * @param mem_ctx talloc context for the return value
130  * @param tids TIDS_INSTANCE handling the request
131  * @param req incoming request
132  * @param resp outgoing response
133  * @return JSON-encoded message containing the TID response
134  */
135 static char *tids_encode_response(TALLOC_CTX *mem_ctx, TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
136 {
137   TR_MSG mresp;
138   char *resp_buf = NULL;
139
140   /* Construct the response message */
141   mresp.msg_type = TID_RESPONSE;
142   tr_msg_set_resp(&mresp, resp);
143
144   /* Encode the message to JSON */
145   resp_buf = tr_msg_encode(mem_ctx, &mresp);
146   if (resp_buf == NULL) {
147     tr_err("tids_encode_response: Error encoding json response.");
148     return NULL;
149   }
150   tr_debug("tids_encode_response: Encoded response: %s", resp_buf);
151
152   /* Success */
153   return resp_buf;
154 }
155
156 /**
157  * Encode/send an error response
158  *
159  * Part of the public interface
160  *
161  * @param tids
162  * @param req
163  * @param err_msg
164  * @return
165  */
166 int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg) {
167   TID_RESP *resp = NULL;
168   int rc = 0;
169
170   if ((!tids) || (!req) || (!err_msg)) {
171     tr_debug("tids_send_err_response: Invalid parameters.");
172     return -1;
173   }
174
175   /* If we already sent a response, don't send another no matter what. */
176   if (req->resp_sent)
177     return 0;
178
179   if (NULL == (resp = tids_create_response(req, tids, req))) {
180     tr_crit("tids_send_err_response: Can't create response.");
181     return -1;
182   }
183
184   /* mark this as an error response, and include the error message */
185   resp->result = TID_ERROR;
186   resp->err_msg = tr_new_name((char *)err_msg);
187   resp->error_path = req->path;
188
189   rc = tids_send_response(tids, req, resp);
190
191   tid_resp_free(resp);
192   return rc;
193 }
194
195 /**
196  * Encode/send a response
197  *
198  * Part of the public interface
199  *
200  * @param tids
201  * @param req
202  * @param resp
203  * @return
204  */
205 int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
206 {
207   int err;
208   char *resp_buf;
209
210   if ((!tids) || (!req) || (!resp)) {
211     tr_debug("tids_send_response: Invalid parameters.");
212     return -1;
213   }
214
215   /* Never send a second response if we already sent one. */
216   if (req->resp_sent)
217     return 0;
218
219   resp_buf = tids_encode_response(NULL, tids, req, resp);
220   if (resp_buf == NULL) {
221     tr_err("tids_send_response: Error encoding json response.");
222     tr_audit_req(req);
223     return -1;
224   }
225
226   tr_debug("tids_send_response: Encoded response: %s", resp_buf);
227
228   /* If external logging is enabled, fire off a message */
229   /* TODO Can be moved to end once segfault in gsscon_write_encrypted_token fixed */
230   tr_audit_resp(resp);
231
232   /* Send the response over the connection */
233   err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf,
234                                             strlen(resp_buf) + 1);
235   if (err) {
236     tr_notice("tids_send_response: Error sending response over connection.");
237     tr_audit_req(req);
238     return -1;
239   }
240
241   /* indicate that a response has been sent for this request */
242   req->resp_sent = 1;
243
244   free(resp_buf);
245
246   return 0;
247 }
248
249 /**
250  * Callback to process a request and produce a response
251  *
252  * @param req_str JSON-encoded request
253  * @param data pointer to a TIDS_INSTANCE
254  * @return pointer to the response string or null to send no response
255  */
256 static char *tids_req_cb(TALLOC_CTX *mem_ctx, const char *req_str, void *data)
257 {
258   TIDS_INSTANCE *tids = talloc_get_type_abort(data, TIDS_INSTANCE);
259   TR_MSG *mreq = NULL;
260   TID_REQ *req = NULL;
261   TID_RESP *resp = NULL;
262   char *resp_str = NULL;
263   int rc = 0;
264
265   mreq = tr_msg_decode(req_str, strlen(req_str)); // allocates memory on success!
266   if (mreq == NULL) {
267     tr_debug("tids_req_cb: Error decoding request.");
268     return NULL;
269   }
270
271   /* If this isn't a TID Request, just drop it. */
272   if (mreq->msg_type != TID_REQUEST) {
273     tr_msg_free_decoded(mreq);
274     tr_debug("tids_req_cb: Not a TID request, dropped.");
275     return NULL;
276   }
277
278   /* Get a handle on the request itself. Don't free req - it belongs to mreq */
279   req = tr_msg_get_req(mreq);
280
281   /* Allocate a response structure and populate common fields. The resp is in req's talloc context,
282    * which will be cleaned up when mreq is freed. */
283   resp = tids_create_response(req, tids, req);
284   if (resp == NULL) {
285     /* If we were unable to create a response, we cannot reply. Log an
286      * error if we can, then drop the request. */
287     tr_msg_free_decoded(mreq);
288     tr_crit("tids_req_cb: Error creating response structure.");
289     return NULL;
290   }
291
292   /* Handle the request and fill in resp */
293   rc = tids_handle_request(tids, req, resp);
294   if (rc < 0) {
295     tr_debug("tids_req_cb: Error from tids_handle_request(), rc = %d.", rc);
296     /* Fall through, to send the response, either way */
297   }
298
299   /* Convert the completed response into an encoded response */
300   resp_str = tids_encode_response(mem_ctx, tids, req, resp);
301
302   /* Finished; free the request and return */
303   tr_msg_free_decoded(mreq); // this frees req and resp, too
304   return resp_str;
305 }
306
307 TIDS_INSTANCE *tids_new(TALLOC_CTX *mem_ctx)
308 {
309   return talloc_zero(mem_ctx, TIDS_INSTANCE);
310 }
311
312 /**
313  * Create a new TIDS instance
314  *
315  * Deprecated: exists for ABI compatibility, but tids_new() should be used instead
316  *
317  */
318 TIDS_INSTANCE *tids_create(void)
319 {
320   return talloc_zero(NULL, TIDS_INSTANCE);
321 }
322 /* Get a listener for tids requests, returns its socket fd. Accept
323  * connections with tids_accept() */
324 nfds_t tids_get_listener(TIDS_INSTANCE *tids,
325                          TIDS_REQ_FUNC *req_handler,
326                          tids_auth_func *auth_handler,
327                          const char *hostname,
328                          unsigned int port,
329                          void *cookie,
330                          int *fd_out,
331                          size_t max_fd)
332 {
333   nfds_t n_fd = 0;
334   nfds_t ii = 0;
335
336   tids->tids_port = port;
337   n_fd = tr_sock_listen_all(port, fd_out, max_fd);
338
339   if (n_fd == 0)
340     tr_err("tids_get_listener: Error opening port %d");
341   else {
342     /* opening port succeeded */
343     tr_info("tids_get_listener: Opened port %d.", port);
344     
345     /* make this socket non-blocking */
346     for (ii=0; ii<n_fd; ii++) {
347       if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
348         tr_err("tids_get_listener: Error setting O_NONBLOCK.");
349         for (ii=0; ii<n_fd; ii++) {
350           close(fd_out[ii]);
351           fd_out[ii]=-1;
352         }
353         n_fd = 0;
354         break;
355       }
356     }
357   }
358
359   if (n_fd > 0) {
360     /* store the caller's request handler & cookie */
361     tids->req_handler = req_handler;
362     tids->auth_handler = auth_handler;
363     tids->hostname = hostname;
364     tids->cookie = cookie;
365   }
366
367   return (int)n_fd;
368 }
369
370 /* Accept and process a connection on a port opened with tids_get_listener() */
371 int tids_accept(TIDS_INSTANCE *tids, int listen)
372 {
373   int conn=-1;
374   int pid=-1;
375
376   if (0 > (conn = accept(listen, NULL, NULL))) {
377     perror("Error from TIDS Server accept()");
378     return 1;
379   }
380
381   if (0 > (pid = fork())) {
382     perror("Error on fork()");
383     return 1;
384   }
385
386   if (pid == 0) {
387     close(listen);
388     tr_gss_handle_connection(conn,
389                              "trustidentity", tids->hostname, /* acceptor name */
390                              tids->auth_handler, tids->cookie, /* auth callback and cookie */
391                              tids_req_cb, tids /* req callback and cookie */
392     );
393     close(conn);
394     exit(0); /* exit to kill forked child process */
395   } else {
396     close(conn);
397   }
398
399   /* clean up any processes that have completed  (TBD: move to main loop?) */
400   while (waitpid(-1, 0, WNOHANG) > 0);
401
402   return 0;
403 }
404
405 /* Process tids requests forever. Should not return except on error. */
406 int tids_start (TIDS_INSTANCE *tids,
407                 TIDS_REQ_FUNC *req_handler,
408                 tids_auth_func *auth_handler,
409                 const char *hostname,
410                 unsigned int port,
411                 void *cookie)
412 {
413   int fd[TR_MAX_SOCKETS]={0};
414   nfds_t n_fd=0;
415   struct pollfd poll_fd[TR_MAX_SOCKETS]={{0}};
416   int ii=0;
417
418   n_fd = tids_get_listener(tids, req_handler, auth_handler, hostname, port, cookie, fd, TR_MAX_SOCKETS);
419   if (n_fd <= 0) {
420     perror ("Error from tids_listen()");
421     return 1;
422   }
423
424   tr_info("Trust Path Query Server starting on host %s:%d.", hostname, port);
425
426   /* set up the poll structs */
427   for (ii=0; ii<n_fd; ii++) {
428     poll_fd[ii].fd=fd[ii];
429     poll_fd[ii].events=POLLIN;
430   }
431
432   while(1) {    /* accept incoming conns until we are stopped */
433     /* clear out events from previous iteration */
434     for (ii=0; ii<n_fd; ii++)
435       poll_fd[ii].revents=0;
436
437     /* wait indefinitely for a connection */
438     if (poll(poll_fd, n_fd, -1) < 0) {
439       perror("Error from poll()");
440       return 1;
441     }
442
443     /* fork handlers for any sockets that have data */
444     for (ii=0; ii<n_fd; ii++) {
445       if (poll_fd[ii].revents == 0)
446         continue;
447
448       if ((poll_fd[ii].revents & POLLERR) || (poll_fd[ii].revents & POLLNVAL)) {
449         perror("Error polling fd");
450         continue;
451       }
452
453       if (poll_fd[ii].revents & POLLIN) {
454         if (tids_accept(tids, poll_fd[ii].fd))
455           tr_err("tids_start: error in tids_accept().");
456       }
457     }
458   }
459
460   return 1;     /* should never get here, loops "forever" */
461 }
462
463 void tids_destroy (TIDS_INSTANCE *tids)
464 {
465   /* clean up logfiles */
466   tr_log_close();
467
468   if (tids)
469     free(tids);
470 }