2 * Copyright (c) 2012, 2015, JANET(UK)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
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.
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.
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.
40 #include <sys/socket.h>
45 #include <tid_internal.h>
49 #include <tr_socket.h>
54 * Create a response with minimal fields filled in
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
60 static TID_RESP *tids_create_response(TALLOC_CTX *mem_ctx, TID_REQ *req)
65 if (NULL == (resp = tid_resp_new(mem_ctx))) {
66 tr_crit("tids_create_response: Error allocating response structure.");
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.");
78 if (NULL == (resp->orig_coi = tr_dup_name(req->orig_coi))) {
79 tr_crit("tids_create_response: Error allocating fields in response.");
87 if ((!success) && (resp!=NULL)) {
94 static int tids_handle_request(TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
98 /* Check that this is a valid TID Request. If not, send an error return. */
100 (!(req->rp_realm)) ||
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"));
109 tr_debug("tids_handle_request: adding self to req path.");
110 tid_req_add_path(req, tids->hostname, tids->tids_port);
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"));
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 */
131 * Produces a JSON-encoded msg containing the TID response
133 * @param mem_ctx talloc context for the return value
134 * @param resp outgoing response
135 * @return JSON-encoded message containing the TID response
137 static char *tids_encode_response(TALLOC_CTX *mem_ctx, TID_RESP *resp)
140 char *resp_buf = NULL;
142 /* Construct the response message */
143 mresp.msg_type = TID_RESPONSE;
144 tr_msg_set_resp(&mresp, resp);
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.");
152 tr_debug("tids_encode_response: Encoded response: %s", resp_buf);
159 * Encode/send an error response
161 * Part of the public interface
168 int tids_send_err_response (TIDS_INSTANCE *tids, TID_REQ *req, const char *err_msg) {
169 TID_RESP *resp = NULL;
172 if ((!tids) || (!req) || (!err_msg)) {
173 tr_debug("tids_send_err_response: Invalid parameters.");
177 /* If we already sent a response, don't send another no matter what. */
181 if (NULL == (resp = tids_create_response(req, req))) {
182 tr_crit("tids_send_err_response: Can't create response.");
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;
191 rc = tids_send_response(tids, req, resp);
198 * Encode/send a response
200 * Part of the public interface
202 * @param tids not actually used, but kept for ABI compatibility
207 int tids_send_response (TIDS_INSTANCE *tids, TID_REQ *req, TID_RESP *resp)
212 if ((!tids) || (!req) || (!resp)) {
213 tr_debug("tids_send_response: Invalid parameters.");
217 /* Never send a second response if we already sent one. */
221 resp_buf = tids_encode_response(NULL, NULL);
222 if (resp_buf == NULL) {
223 tr_err("tids_send_response: Error encoding json response.");
228 tr_debug("tids_send_response: Encoded response: %s", resp_buf);
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 */
234 /* Send the response over the connection */
235 err = gsscon_write_encrypted_token (req->conn, req->gssctx, resp_buf,
236 strlen(resp_buf) + 1);
238 tr_notice("tids_send_response: Error sending response over connection.");
243 /* indicate that a response has been sent for this request */
252 * Callback to process a request and produce a response
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
258 static TR_MSG *tids_req_cb(TALLOC_CTX *mem_ctx, TR_MSG *mreq, void *data)
260 TALLOC_CTX *tmp_ctx = talloc_new(NULL);
261 TIDS_INSTANCE *tids = talloc_get_type_abort(data, TIDS_INSTANCE);
263 TID_RESP *resp = NULL;
264 TR_MSG *resp_msg = NULL; /* this is the return value */
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.");
273 /* Get a handle on the request itself. Don't free req - it belongs to mreq */
274 req = tr_msg_get_req(mreq);
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.");
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);
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 */
295 /* Now officially assign the response to the message. */
296 tr_msg_set_resp(resp_msg, resp);
298 /* Handle the request and fill in resp */
299 rc = tids_handle_request(tids, req, resp);
301 tr_debug("tids_req_cb: Error from tids_handle_request(), rc = %d.", rc);
302 /* Fall through, to send the response, either way */
305 /* put the response message in the caller's context */
306 talloc_steal(mem_ctx, resp_msg);
309 talloc_free(tmp_ctx);
313 static int tids_destructor(void *object)
315 TIDS_INSTANCE *tids = talloc_get_type_abort(object, TIDS_INSTANCE);
317 g_array_unref(tids->pids);
321 TIDS_INSTANCE *tids_new(TALLOC_CTX *mem_ctx)
323 TIDS_INSTANCE *tids = talloc_zero(mem_ctx, TIDS_INSTANCE);
325 tids->pids = g_array_new(FALSE, FALSE, sizeof(struct tid_process));
326 if (tids->pids == NULL) {
330 talloc_set_destructor((void *)tids, tids_destructor);
336 * Create a new TIDS instance
338 * Deprecated: exists for ABI compatibility, but tids_new() should be used instead
341 TIDS_INSTANCE *tids_create(void)
343 return tids_new(NULL);
346 /* Get a listener for tids requests, returns its socket fd. Accept
347 * connections with tids_accept() */
348 nfds_t tids_get_listener(TIDS_INSTANCE *tids,
349 TIDS_REQ_FUNC *req_handler,
350 tids_auth_func *auth_handler,
351 const char *hostname,
360 tids->tids_port = port;
361 n_fd = tr_sock_listen_all(port, fd_out, max_fd);
364 tr_err("tids_get_listener: Error opening port %d");
366 /* opening port succeeded */
367 tr_info("tids_get_listener: Opened port %d.", port);
369 /* make this socket non-blocking */
370 for (ii=0; ii<n_fd; ii++) {
371 if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
372 tr_err("tids_get_listener: Error setting O_NONBLOCK.");
373 for (ii=0; ii<n_fd; ii++) {
384 /* store the caller's request handler & cookie */
385 tids->req_handler = req_handler;
386 tids->auth_handler = auth_handler;
387 tids->hostname = hostname;
388 tids->cookie = cookie;
394 /* Accept and process a connection on a port opened with tids_get_listener() */
395 int tids_accept(TIDS_INSTANCE *tids, int listen)
400 struct tid_process tp = {0};
402 if (0 > (conn = accept(listen, NULL, NULL))) {
403 perror("Error from TIDS Server accept()");
407 if (0 > pipe(pipe_fd)) {
408 perror("Error on pipe()");
411 /* pipe_fd[0] is for reading, pipe_fd[1] is for writing */
413 if (0 > (pid = fork())) {
414 perror("Error on fork()");
419 close(pipe_fd[0]); /* child only writes */
421 tr_gss_handle_connection(conn,
422 "trustidentity", tids->hostname, /* acceptor name */
423 tids->auth_handler, tids->cookie, /* auth callback and cookie */
424 tids_req_cb, tids /* req callback and cookie */
426 if (write(pipe_fd[1], "OK\0", 3) < 0)
427 tr_crit("tids_accept: child process unable to write to pipe");
430 exit(0); /* exit to kill forked child process */
433 /* Only the parent process gets here */
434 close(pipe_fd[1]); /* parent only listens */
435 close(conn); /* connection belongs to the child */
437 tp.read_fd = pipe_fd[0];
438 g_array_append_val(tids->pids, tp); /* remember the PID of our child process */
440 /* clean up any processes that have completed */
441 tids_sweep_procs(tids);
446 * Clean up any finished TID request processes
448 * This is called by the main process after forking each TID request. If you want to be
449 * sure finished processes are cleaned up promptly even during a lull in TID requests,
450 * this can be called from the main thread of the main process. It is not thread-safe,
451 * so should not be used from sub-threads. It should not be called by child processes -
452 * this would probably be harmless but ineffective.
456 void tids_sweep_procs(TIDS_INSTANCE *tids)
459 struct tid_process tp = {0};
460 char result[10] = {0};
465 /* loop backwards over the array so we can remove elements as we go */
466 for (ii=tids->pids->len; ii > 0; ii--) {
467 /* ii-1 is the current index - get our own copy, we may destroy the list's copy */
468 tp = g_array_index(tids->pids, struct tid_process, ii-1);
470 wait_rc = waitpid(tp.pid, &status, WNOHANG);
472 continue; /* process still running */
475 /* invalid options will probably keep being invalid, report that condition */
477 tr_crit("tids_sweep_procs: waitpid called with invalid options");
479 /* If we got ECHILD, that means the PID was invalid; we'll assume the process was
480 * terminated and we missed it. For all other errors, move on
481 * to the next PID to check. */
485 tr_warning("tid_sweep_procs: TID process %d disappeared", tp.pid);
488 /* remove the item (we still have a copy of the data) */
489 g_array_remove_index_fast(tids->pids, ii-1); /* disturbs only indices >= ii-1 which we've already handled */
491 /* Report exit status unless we got ECHILD above or somehow waitpid returned the wrong pid */
492 if (wait_rc == tp.pid) {
493 if (WIFEXITED(status)) {
494 tr_debug("tids_sweep_procs: TID process %d exited with status %d.", tp.pid, WTERMSIG(status));
495 } else if (WIFSIGNALED(status)) {
496 tr_debug("tids_sweep_procs: TID process %d terminated by signal %d.", tp.pid, WTERMSIG(status));
498 } else if (wait_rc > 0) {
499 tr_err("tids_sweep_procs: waitpid returned pid %d, expected %d", wait_rc, tp.pid);
502 /* read the pipe - if the TID request worked, it will have written status before terminating */
503 result_len = read(tp.read_fd, result, sizeof(result)/sizeof(result[0]));
506 if ((result_len > 0) && (strcmp(result, "OK") == 0)) {
508 tr_debug("tids_sweep_procs: TID process %d succeeded", tp.pid);
511 tr_debug("tids_sweep_procs: TID process %d failed", tp.pid);
516 /* Process tids requests forever. Should not return except on error. */
517 int tids_start (TIDS_INSTANCE *tids,
518 TIDS_REQ_FUNC *req_handler,
519 tids_auth_func *auth_handler,
520 const char *hostname,
524 int fd[TR_MAX_SOCKETS]={0};
526 struct pollfd poll_fd[TR_MAX_SOCKETS]={{0}};
529 n_fd = tids_get_listener(tids, req_handler, auth_handler, hostname, port, cookie, fd, TR_MAX_SOCKETS);
531 perror ("Error from tids_listen()");
535 tr_info("Trust Path Query Server starting on host %s:%d.", hostname, port);
537 /* set up the poll structs */
538 for (ii=0; ii<n_fd; ii++) {
539 poll_fd[ii].fd=fd[ii];
540 poll_fd[ii].events=POLLIN;
543 while(1) { /* accept incoming conns until we are stopped */
544 /* clear out events from previous iteration */
545 for (ii=0; ii<n_fd; ii++)
546 poll_fd[ii].revents=0;
548 /* wait indefinitely for a connection */
549 if (poll(poll_fd, n_fd, -1) < 0) {
550 perror("Error from poll()");
554 /* fork handlers for any sockets that have data */
555 for (ii=0; ii<n_fd; ii++) {
556 if (poll_fd[ii].revents == 0)
559 if ((poll_fd[ii].revents & POLLERR) || (poll_fd[ii].revents & POLLNVAL)) {
560 perror("Error polling fd");
564 if (poll_fd[ii].revents & POLLIN) {
565 if (tids_accept(tids, poll_fd[ii].fd))
566 tr_err("tids_start: error in tids_accept().");
571 return 1; /* should never get here, loops "forever" */
574 void tids_destroy (TIDS_INSTANCE *tids)
576 /* clean up logfiles */