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