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