Use json_is_true() in place of json_boolean_value() for compatibility
[trust_router.git] / tr / tr_tid.c
1 /*
2  * Copyright (c) 2016, 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 <talloc.h>
36
37 #include <trust_router/tr_dh.h>
38 #include <tid_internal.h>
39 #include <tr_filter.h>
40 #include <tr_comm.h>
41 #include <tr_idp.h>
42 #include <tr_rp.h>
43 #include <tr_rp_client.h>
44 #include <tr_event.h>
45 #include <tr_debug.h>
46 #include <gsscon.h>
47 #include <trp_route.h>
48 #include <trp_internal.h>
49 #include <tr_config.h>
50 #include <tr_mq.h>
51 #include <tr_util.h>
52 #include <tr_tid.h>
53 #include <tr_comm.h>
54
55 /* Structure to hold data for the tid response callback */
56 typedef struct tr_resp_cookie {
57   int thread_id;
58   TID_RESP *resp;
59 } TR_RESP_COOKIE;
60
61 /* hold a tids instance and a config manager */
62 struct tr_tids_event_cookie {
63   TIDS_INSTANCE *tids;
64   TR_CFG_MGR *cfg_mgr;
65   TRPS_INSTANCE *trps;
66 };
67
68 static void tr_tidc_resp_handler(TIDC_INSTANCE *tidc, 
69                                  TID_REQ *req,
70                                  TID_RESP *resp, 
71                                  void *resp_cookie)
72 {
73   TR_RESP_COOKIE *cookie=talloc_get_type_abort(resp_cookie, TR_RESP_COOKIE);
74
75   tr_debug("tr_tidc_resp_handler: Response received! Realm = %s, Community = %s, result = %s.",
76            resp->realm->buf,
77            resp->comm->buf,
78            (TID_SUCCESS==resp->result)?"success":"error");
79
80   if (resp->error_path!=NULL)
81     tr_debug("tr_tids_resp_handler: error_path is set.");
82   cookie->resp=tid_resp_dup(cookie, resp);
83 }
84
85 /* data for AAA req forwarding threads */
86 struct tr_tids_fwd_cookie {
87   int thread_id;
88   pthread_mutex_t mutex; /* lock on the mq (separate from the locking within the mq, see below) */
89   TR_MQ *mq; /* messages from thread to main process; set to NULL to disable response */
90   TR_AAA_SERVER *aaa; /* AAA server to contact */
91   DH *dh_params;
92   TID_REQ *fwd_req; /* the req to duplicate */
93 };
94
95 static int tr_tids_fwd_cookie_destructor(void *obj)
96 {
97   struct tr_tids_fwd_cookie *c=talloc_get_type_abort(obj, struct tr_tids_fwd_cookie);
98   if (c->dh_params!=NULL)
99     tr_destroy_dh_params(c->dh_params);
100   return 0;
101 }
102
103 /* Block until we get the lock, returns 0 on success.
104  * The mutex is used to protect changes to the mq pointer in
105  * a thread's cookie. The master thread sets this to null to indicate
106  * that it has abandoned the thread and the message queue is no longer
107  * valid. This is unrelated to the locking in the message queue
108  * implementation itself. */
109 static int tr_tids_fwd_get_mutex(struct tr_tids_fwd_cookie *cookie)
110 {
111   if (cookie==NULL)
112     return -1;
113
114   return (pthread_mutex_lock(&(cookie->mutex)));
115 }
116
117 static int tr_tids_fwd_release_mutex(struct tr_tids_fwd_cookie *cookie)
118 {
119   if (cookie==NULL)
120     return -1;
121
122   return (pthread_mutex_unlock(&(cookie->mutex)));
123 }
124
125 /* values for messages */
126 #define TR_TID_MQMSG_SUCCESS "tid success"
127 #define TR_TID_MQMSG_FAILURE "tid failure"
128
129 /* Thread main for sending and receiving a request to a single AAA server */
130 static void *tr_tids_req_fwd_thread(void *arg)
131 {
132   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
133   struct tr_tids_fwd_cookie *args=talloc_get_type_abort(arg, struct tr_tids_fwd_cookie);
134   TIDC_INSTANCE *tidc=tidc_create();
135   TR_MQ_MSG *msg=NULL;
136   TR_RESP_COOKIE *cookie=NULL;
137   char *aaa_hostname = NULL;
138   int aaa_port;
139   int rc=0;
140   int success=0;
141
142   talloc_steal(tmp_ctx, args); /* take responsibility for the cookie */
143
144   if (tidc!=NULL)
145     talloc_steal(tmp_ctx, tidc);
146
147   /* create the cookie we will use for our response */
148   cookie=talloc(tmp_ctx, TR_RESP_COOKIE);
149   if (cookie==NULL) {
150     tr_crit("tr_tids_req_fwd_thread: unable to allocate response cookie.");
151     success=0;
152     goto cleanup;
153   }
154   cookie->thread_id=args->thread_id;
155   tr_debug("tr_tids_req_fwd_thread: thread %d started.", cookie->thread_id);
156
157   /* Create a TID client instance */
158   if (tidc==NULL) {
159     tr_crit("tr_tids_req_fwd_thread: Unable to allocate TIDC instance.");
160     /*tids_send_err_response(tids, orig_req, "Memory allocation failure");*/
161     /* TODO: encode reason for failure */
162     success=0;
163     goto cleanup;
164   }
165
166   /* Set-up TID connection */
167   aaa_hostname = tr_name_strdup(tr_aaa_server_get_hostname(args->aaa));
168   if (aaa_hostname == NULL) {
169     tr_crit("tr_tids_req_fwd_thread: unable to allocate AAA hostname string");
170     success=0;
171     goto cleanup;
172   }
173   aaa_port = tr_aaa_server_get_port(args->aaa);
174   if ((aaa_port <= 0) || (aaa_port > 65535)) {
175     tr_notice("tr_tids_req_fwd_thread: invalid port (%d) for %s", aaa_port, aaa_hostname);
176     success=0;
177     goto cleanup;
178   }
179
180   if (-1==(args->fwd_req->conn = tidc_open_connection(tidc, 
181                                                       aaa_hostname,
182                                                       aaa_port,
183                                                       &(args->fwd_req->gssctx)))) {
184     tr_notice("tr_tids_req_fwd_thread: Error in tidc_open_connection.");
185     /* tids_send_err_response(tids, orig_req, "Can't open connection to next hop TIDS"); */
186     /* TODO: encode reason for failure */
187     success=0;
188     goto cleanup;
189   };
190   tr_debug("tr_tids_req_fwd_thread: thread %d opened TID connection to %s:%d.",
191            cookie->thread_id, aaa_hostname, aaa_port);
192
193   /* Send a TID request. */
194   if (0 > (rc = tidc_fwd_request(tidc, args->fwd_req, tr_tidc_resp_handler, (void *)cookie))) {
195     tr_notice("Error from tidc_fwd_request, rc = %d.", rc);
196     success=0;
197     goto cleanup;
198   }
199   /* cookie->resp should now contain our copy of the response */
200   success=1;
201   tr_debug("tr_tids_req_fwd_thread: thread %d received response.", cookie->thread_id);
202
203 cleanup:
204   /* Notify parent thread of the response, if it's still listening. */
205   if (0!=tr_tids_fwd_get_mutex(args)) {
206     tr_notice("tr_tids_req_fwd_thread: thread %d unable to acquire mutex.", cookie->thread_id);
207   } else if (NULL!=args->mq) {
208     /* mq is still valid, so we can queue our response */
209     tr_debug("tr_tids_req_fwd_thread: thread %d using valid msg queue.", cookie->thread_id);
210     if (success)
211       msg= tr_mq_msg_new(tmp_ctx, TR_TID_MQMSG_SUCCESS);
212     else
213       msg= tr_mq_msg_new(tmp_ctx, TR_TID_MQMSG_FAILURE);
214
215     if (msg==NULL)
216       tr_notice("tr_tids_req_fwd_thread: thread %d unable to allocate response msg.", cookie->thread_id);
217
218     tr_mq_msg_set_payload(msg, (void *)cookie, NULL);
219     if (NULL!=cookie)
220       talloc_steal(msg, cookie); /* attach this to the msg so we can forget about it */
221     tr_mq_add(args->mq, msg);
222     talloc_steal(NULL, args); /* take out of our tmp_ctx; master thread now responsible for freeing */
223     tr_debug("tr_tids_req_fwd_thread: thread %d queued response message.", cookie->thread_id);
224     if (0!=tr_tids_fwd_release_mutex(args))
225       tr_notice("tr_tids_req_fwd_thread: Error releasing mutex.");
226   }
227
228   if (aaa_hostname != NULL)
229     free(aaa_hostname);
230
231   talloc_free(tmp_ctx);
232   return NULL;
233 }
234
235 /* Merges r2 into r1 if they are compatible. */
236 static TID_RC tr_tids_merge_resps(TID_RESP *r1, TID_RESP *r2)
237 {
238   /* ensure these are compatible replies */
239   if ((r1->result!=TID_SUCCESS) || (r2->result!=TID_SUCCESS))
240     return TID_ERROR;
241
242   if ((0 == tr_name_cmp(r1->rp_realm, r2->rp_realm))
243       && (0 == tr_name_cmp(r1->realm, r2->realm))
244       && ( (0 == tr_name_cmp(r1->comm, r2->comm))
245            || (0 == tr_name_cmp(r1->comm, r2->orig_coi))
246            || (0 == tr_name_cmp(r1->orig_coi, r2->comm)))) {
247
248     tid_srvr_blk_add(r1->servers, tid_srvr_blk_dup(r1, r2->servers));
249     return TID_SUCCESS;
250   }
251
252   return TID_ERROR;
253 }
254
255 enum map_coi_result {
256   MAP_COI_SUCCESS = 0,
257   MAP_COI_MAP_NOT_REQUIRED,
258   MAP_COI_ALREADY_MAPPED,
259   MAP_COI_NO_APC,
260   MAP_COI_INVALID_APC,
261   MAP_COI_UNKNOWN_COMM,
262   MAP_COI_ERROR
263 };
264
265 static enum map_coi_result map_coi(TR_COMM_TABLE *ctable, TID_REQ *req)
266 {
267   TR_COMM *orig_comm;
268   TR_NAME *apc_name;
269   TR_COMM *apc;
270   TR_APC *apcs;
271
272   if (tid_req_get_orig_coi(req) != NULL)
273     return MAP_COI_ALREADY_MAPPED;
274
275   /* look up the community */
276   orig_comm = tr_comm_table_find_comm(ctable, tid_req_get_comm(req));
277   if (orig_comm == NULL)
278     return MAP_COI_UNKNOWN_COMM;
279
280   if (tr_comm_get_type(orig_comm) == TR_COMM_APC)
281     return MAP_COI_MAP_NOT_REQUIRED; /* it was already an APC, no mapping to do */
282
283   /* use first (only) APC. These are just APC names  */
284   apcs = tr_comm_get_apcs(orig_comm);
285   if ((!apcs) || (!tr_apc_get_id(apcs)))
286     return MAP_COI_NO_APC;
287
288   /* get our own copy of the APC name */
289   apc_name = tr_dup_name(tr_apc_get_id(apcs));
290   if (apc_name == NULL) {
291     tr_err("map_coi: Error allocating apc_name");
292     return MAP_COI_ERROR;
293   }
294
295   /* Check that the APC is configured */
296   apc = tr_comm_table_find_comm(ctable, apc_name);
297   if (apc == NULL) {
298     tr_free_name(apc_name);
299     return MAP_COI_INVALID_APC;
300   }
301
302   tid_req_set_orig_coi(req, tid_req_get_comm(req)); /* was null, so no need to free anything */
303   tid_req_set_comm(req, apc_name); /* original contents will be freed via orig_coi */
304
305   return MAP_COI_SUCCESS; /* successfully mapped */
306 }
307
308 /**
309  * Process a TID request
310  *
311  * Return value of -1 means to send a TID_ERROR response. Fill in resp->err_msg or it will
312  * be returned as a generic error.
313  *
314  * @param tids
315  * @param orig_req
316  * @param resp
317  * @param cookie_in
318  * @return
319  */
320 static int tr_tids_req_handler(TIDS_INSTANCE *tids,
321                                TID_REQ *orig_req, 
322                                TID_RESP *resp,
323                                void *cookie_in)
324 {
325   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
326   TR_AAA_SERVER *aaa_servers=NULL, *this_aaa=NULL;
327   int n_aaa=0;
328   int idp_shared=0;
329   TR_AAA_SERVER_ITER *aaa_iter=NULL;
330   pthread_t aaa_thread[TR_TID_MAX_AAA_SERVERS];
331   struct tr_tids_fwd_cookie *aaa_cookie[TR_TID_MAX_AAA_SERVERS]={NULL};
332   TID_RESP *aaa_resp[TR_TID_MAX_AAA_SERVERS]={NULL};
333   TR_RP_CLIENT *rp_client=NULL;
334   TR_RP_CLIENT_ITER *rpc_iter=NULL;
335   TID_REQ *fwd_req = NULL;
336   TR_COMM *cfg_comm = NULL;
337   TR_COMM *cfg_apc = NULL;
338   TR_FILTER_ACTION oaction = TR_FILTER_ACTION_REJECT;
339   time_t expiration_interval=0;
340   struct tr_tids_event_cookie *cookie=talloc_get_type_abort(cookie_in, struct tr_tids_event_cookie);
341   TR_CFG_MGR *cfg_mgr=cookie->cfg_mgr;
342   TRPS_INSTANCE *trps=cookie->trps;
343   TRP_ROUTE *route=NULL;
344   TR_MQ *mq=NULL;
345   TR_MQ_MSG *msg=NULL;
346   unsigned int n_responses=0;
347   unsigned int n_failed=0;
348   struct timespec ts_abort={0};
349   unsigned int resp_frac_numer=cfg_mgr->active->internal->tid_resp_numer;
350   unsigned int resp_frac_denom=cfg_mgr->active->internal->tid_resp_denom;
351   TR_RESP_COOKIE *payload=NULL;
352   TR_FILTER_TARGET *target=NULL;
353   int ii=0;
354   int retval=-1;
355
356   if ((!tids) || (!orig_req) || (!resp)) {
357     tr_debug("tr_tids_req_handler: Bad parameters");
358     retval=-1;
359     goto cleanup;
360   }
361
362   tr_debug("tr_tids_req_handler: Request received (conn = %d)! Realm = %s, Comm = %s", orig_req->conn, 
363            orig_req->realm->buf, orig_req->comm->buf);
364   if (orig_req->request_id)
365     tr_debug("tr_tids_req_handler: TID request ID: %.*s", orig_req->request_id->len, orig_req->request_id->buf);
366   else
367     tr_debug("tr_tids_req_handler: TID request ID: none");
368
369   tids->req_count++;
370
371   /* Duplicate the request, so we can modify and forward it */
372   if (NULL == (fwd_req=tid_dup_req(orig_req))) {
373     tr_debug("tr_tids_req_handler: Unable to duplicate request.");
374     retval=-1; /* response will be a generic internal error */
375     goto cleanup;
376   }
377   talloc_steal(tmp_ctx, fwd_req);
378
379   /* cfg_comm is now the community (APC or CoI) of the incoming request */
380   if (NULL == (cfg_comm=tr_comm_table_find_comm(cfg_mgr->active->ctable, orig_req->comm))) {
381     tr_notice("tr_tids_req_hander: Request for unknown comm: %s.", orig_req->comm->buf);
382     tid_resp_set_err_msg(resp, tr_new_name("Unknown community"));
383     retval=-1;
384     goto cleanup;
385   }
386
387   /* We now need to apply the filters associated with the RP client handing us the request.
388    * It is possible (or even likely) that more than one client is associated with the GSS
389    * name we got from the authentication. We will apply all of them in an arbitrary order.
390    * For this to result in well-defined behavior, either only accept or only reject filter
391    * lines should be used, or a unique GSS name must be given for each RP realm. */
392
393   if (!tids->gss_name) {
394     tr_notice("tr_tids_req_handler: No GSS name for incoming request.");
395     tid_resp_set_err_msg(resp, tr_new_name("No GSS name for request"));
396     retval=-1;
397     goto cleanup;
398   }
399
400   /* Keep original constraints, may add more from the filter. These will be added to orig_req as
401    * well. Need to verify that this is acceptable behavior, but it's what we've always done. */
402   fwd_req->cons=orig_req->cons;
403
404   target=tr_filter_target_tid_req(tmp_ctx, orig_req);
405   if (target==NULL) {
406     tr_crit("tid_req_handler: Unable to allocate filter target, cannot apply filter!");
407     tid_resp_set_err_msg(resp, tr_new_name("Incoming TID request filter error"));
408     retval=-1;
409     goto cleanup;
410   }
411
412   rpc_iter=tr_rp_client_iter_new(tmp_ctx);
413   if (rpc_iter==NULL) {
414     tr_err("tid_req_handler: Unable to allocate RP client iterator.");
415     retval=-1;
416     goto cleanup;
417   }
418   for (rp_client=tr_rp_client_iter_first(rpc_iter, cfg_mgr->active->rp_clients);
419        rp_client != NULL;
420        rp_client=tr_rp_client_iter_next(rpc_iter)) {
421
422     if (!tr_gss_names_matches(rp_client->gss_names, tids->gss_name))
423       continue; /* skip any that don't match the GSS name */
424
425     if (TR_FILTER_MATCH == tr_filter_apply(target,
426                                            tr_filter_set_get(rp_client->filters,
427                                                              TR_FILTER_TYPE_TID_INBOUND),
428                                            &(fwd_req->cons),
429                                            &oaction))
430       break; /* Stop looking, oaction is set */
431   }
432
433   /* We get here whether or not a filter matched. If tr_filter_apply() doesn't match, it returns
434    * a default action of reject, so we don't have to check why we exited the loop. */
435   if (oaction != TR_FILTER_ACTION_ACCEPT) {
436     tr_notice("tr_tids_req_handler: Incoming TID request rejected by RP client filter for GSS name %.*s",
437               tids->gss_name->len, tids->gss_name->buf);
438     tid_resp_set_err_msg(resp, tr_new_name("Incoming TID request filter error"));
439     retval = -1;
440     goto cleanup;
441   }
442
443   /* Check that the rp_realm is a member of the community in the request */
444   if (NULL == tr_comm_find_rp(cfg_mgr->active->ctable, cfg_comm, orig_req->rp_realm)) {
445     tr_notice("tr_tids_req_handler: RP Realm (%s) not member of community (%s).",
446               orig_req->rp_realm->buf, orig_req->comm->buf);
447     tid_resp_set_err_msg(resp, tr_new_name("RP community membership error"));
448     retval=-1;
449     goto cleanup;
450   }
451
452   switch(map_coi(cfg_mgr->active->ctable, fwd_req)) {
453     case MAP_COI_MAP_NOT_REQUIRED:
454       cfg_apc = cfg_comm;
455       break;
456
457     case MAP_COI_SUCCESS:
458       cfg_apc = tr_comm_table_find_comm(cfg_mgr->active->ctable, tid_req_get_comm(fwd_req));
459       tr_debug("tr_tids_req_handler: Community %.*s is a COI, mapping to APC %.*s.",
460                tid_req_get_orig_coi(fwd_req)->len, tid_req_get_orig_coi(fwd_req)->buf,
461                tr_comm_get_id(cfg_apc)->len, tr_comm_get_id(cfg_apc)->buf);
462       break;
463
464     case MAP_COI_ALREADY_MAPPED:
465       tr_notice("tr_tids_req_handler: community %.*s is COI but COI to APC mapping already occurred. Dropping request.",
466                 tid_req_get_comm(orig_req)->len, tid_req_get_comm(orig_req)->buf);
467       tid_resp_set_err_msg(resp, tr_new_name("Second COI to APC mapping would result, permitted only once."));
468       retval = -1;
469       goto cleanup;
470
471     case MAP_COI_NO_APC:
472       tr_notice("No valid APC for COI %.*s.",
473                 tid_req_get_comm(orig_req)->len, tid_req_get_comm(orig_req)->buf);
474       tid_resp_set_err_msg(resp, tr_new_name("No valid APC for community"));
475       retval = -1;
476       goto cleanup;
477
478     case MAP_COI_INVALID_APC:
479       tr_notice("tr_tids_req_hander: Request for unknown APC.");
480       tid_resp_set_err_msg(resp, tr_new_name("Unknown APC"));
481       retval = -1;
482       goto cleanup;
483
484     default:
485       tr_notice("tr_tids_req_hander: Unexpected error mapping COI to APC.");
486       retval = -1;
487       goto cleanup;
488   }
489
490   /* cfg_comm is now the original community, and cfg_apc is the APC it belongs to. These
491    * may both be the same. If not, check that rp_realm is a  member of the mapped APC */
492   if ((cfg_apc != cfg_comm)
493       && (NULL == tr_comm_find_rp(cfg_mgr->active->ctable,
494                                   cfg_apc,
495                                   tid_req_get_rp_realm(fwd_req)))) {
496     tr_notice("tr_tids_req_hander: RP Realm (%.*s) not member of mapped APC (%.*s).",
497               tid_req_get_rp_realm(fwd_req)->len, tid_req_get_rp_realm(fwd_req)->buf,
498               tr_comm_get_id(cfg_apc)->len, tr_comm_get_id(cfg_apc)->buf);
499     tid_resp_set_err_msg(resp, tr_new_name("RP community membership error"));
500     retval=-1;
501     goto cleanup;
502   }
503
504   /* Look up the route for forwarding request's community/realm. */
505   tr_debug("tr_tids_req_handler: looking up route.");
506   route=trps_get_selected_route(trps, fwd_req->comm, fwd_req->realm);
507   if (route==NULL) {
508     /* No route. Use default AAA servers if we have them. */
509     tr_debug("tr_tids_req_handler: No route for realm %s, defaulting.", fwd_req->realm->buf);
510     if (NULL == (aaa_servers = tr_default_server_lookup(cfg_mgr->active->default_servers,
511                                                         fwd_req->comm))) {
512       tr_notice("tr_tids_req_handler: No default AAA servers, discarded.");
513       tid_resp_set_err_msg(resp, tr_new_name("No path to AAA Server(s) for realm"));
514       retval = -1;
515       goto cleanup;
516     }
517     idp_shared = 0;
518   } else {
519     /* Found a route. Determine the AAA servers or next hop address for the request we are forwarding. */
520     tr_debug("tr_tids_req_handler: found route.");
521     if (trp_route_is_local(route)) {
522       tr_debug("tr_tids_req_handler: route is local.");
523       aaa_servers = tr_idp_aaa_server_lookup(cfg_mgr->active->ctable->idp_realms,
524                                              fwd_req->realm,
525                                              fwd_req->comm,
526                                              &idp_shared);
527     } else {
528       tr_debug("tr_tids_req_handler: route not local.");
529       aaa_servers = tr_aaa_server_new(tmp_ctx); /* cleaned up via talloc */
530       if (aaa_servers == NULL) {
531         tr_err("tr_tids_req_handler: error allocating next hop");
532         retval=-1;
533         goto cleanup;
534       }
535       tr_aaa_server_set_hostname(aaa_servers, trp_route_dup_next_hop(route));
536       if (tr_aaa_server_get_hostname(aaa_servers) == NULL) {
537         tr_err("tr_tids_req_handler: error allocating next hop");
538         retval=-1;
539         goto cleanup;
540       }
541       tr_aaa_server_set_port(aaa_servers, trp_route_get_next_hop_port(route));
542       idp_shared = 0;
543     }
544
545     /* Since we aren't defaulting, check idp coi and apc membership of the original request */
546     if (NULL == (tr_comm_find_idp(cfg_mgr->active->ctable, cfg_comm, orig_req->realm))) {
547       tr_notice("tr_tids_req_handler: IDP Realm (%s) not member of community (%s).", orig_req->realm->buf, cfg_comm->id->buf);
548       tid_resp_set_err_msg(resp, tr_new_name("IDP community membership error"));
549       retval=-1;
550       goto cleanup;
551     }
552     if ( cfg_apc && (NULL == (tr_comm_find_idp(cfg_mgr->active->ctable, cfg_apc, orig_req->realm)))) {
553       tr_notice("tr_tids_req_handler: IDP Realm (%s) not member of APC (%s).", orig_req->realm->buf, cfg_apc->id->buf);
554       tid_resp_set_err_msg(resp, tr_new_name("IDP APC membership error"));
555       retval=-1;
556       goto cleanup;
557     }
558   }
559
560   /* Make sure we came through with a AAA server. If not, we can't handle the request.
561    * Report using the original request, not translated values. */
562   if (NULL == aaa_servers) {
563     tr_notice("tr_tids_req_handler: no route or AAA server for realm (%s) in community (%s).",
564               orig_req->realm->buf, orig_req->comm->buf);
565     tid_resp_set_err_msg(resp, tr_new_name("Missing trust route error"));
566     retval = -1;
567     goto cleanup;
568   }
569
570   /* send a TID request to the AAA server(s), and get the answer(s) */
571   tr_debug("tr_tids_req_handler: sending TID request(s).");
572   /* Use the smaller of the APC's expiration interval and the expiration interval of the incoming request */
573   expiration_interval = cfg_apc->expiration_interval;
574   if (fwd_req->expiration_interval)
575     fwd_req->expiration_interval =  (expiration_interval < fwd_req->expiration_interval) ? expiration_interval : fwd_req->expiration_interval;
576   else
577     fwd_req->expiration_interval = expiration_interval;
578
579   /* Set up message queue for replies from req forwarding threads */
580   mq=tr_mq_new(tmp_ctx);
581   if (mq==NULL) {
582     tr_notice("tr_tids_req_handler: unable to allocate message queue.");
583     retval=-1;
584     goto cleanup;
585   }
586   tr_debug("tr_tids_req_handler: message queue allocated.");
587
588   /* start threads */
589   aaa_iter=tr_aaa_server_iter_new(tmp_ctx);
590   if (aaa_iter==NULL) {
591     tr_notice("tr_tids_req_handler: unable to allocate AAA server iterator.");
592     retval=-1;
593     goto cleanup;
594   }
595   for (n_aaa=0, this_aaa=tr_aaa_server_iter_first(aaa_iter, aaa_servers);
596        this_aaa!=NULL;
597        n_aaa++, this_aaa=tr_aaa_server_iter_next(aaa_iter)) {
598     tr_debug("tr_tids_req_handler: Preparing to start thread %d.", n_aaa);
599
600     aaa_cookie[n_aaa]=talloc(tmp_ctx, struct tr_tids_fwd_cookie);
601     if (aaa_cookie[n_aaa]==NULL) {
602       tr_notice("tr_tids_req_handler: unable to allocate cookie for AAA thread %d.", n_aaa);
603       retval=-1;
604       goto cleanup;
605     }
606     talloc_set_destructor((void *)(aaa_cookie[n_aaa]), tr_tids_fwd_cookie_destructor);
607     /* fill in the cookie. To ensure the thread has valid data even if we exit first and
608      * abandon it, duplicate anything pointed to (except the mq). */
609     aaa_cookie[n_aaa]->thread_id=n_aaa;
610     if (0!=pthread_mutex_init(&(aaa_cookie[n_aaa]->mutex), NULL)) {
611       tr_notice("tr_tids_req_handler: unable to init mutex for AAA thread %d.", n_aaa);
612       retval=-1;
613       goto cleanup;
614     }
615     aaa_cookie[n_aaa]->mq=mq;
616     aaa_cookie[n_aaa]->aaa=this_aaa;
617     aaa_cookie[n_aaa]->dh_params=tr_dh_dup(orig_req->tidc_dh);
618     aaa_cookie[n_aaa]->fwd_req=tid_dup_req(fwd_req);
619     talloc_steal(aaa_cookie[n_aaa], aaa_cookie[n_aaa]->fwd_req);
620     tr_debug("tr_tids_req_handler: cookie %d initialized.", n_aaa);
621
622     /* Take the cookie out of tmp_ctx before starting thread. If thread starts, it becomes
623      * responsible for freeing it until it queues a response. If we did not do this, the possibility
624      * exists that this function exits, freeing the cookie, before the thread takes the cookie
625      * out of our tmp_ctx. This would cause a segfault or talloc error in the thread. */
626     talloc_steal(NULL, aaa_cookie[n_aaa]);
627     if (0!=pthread_create(&(aaa_thread[n_aaa]), NULL, tr_tids_req_fwd_thread, aaa_cookie[n_aaa])) {
628       talloc_steal(tmp_ctx, aaa_cookie[n_aaa]); /* thread start failed; steal this back */
629       tr_notice("tr_tids_req_handler: unable to start AAA thread %d.", n_aaa);
630       retval=-1;
631       goto cleanup;
632     }
633     tr_debug("tr_tids_req_handler: thread %d started.", n_aaa);
634   }
635
636   /* determine expiration time */
637   if (0!=tr_mq_pop_timeout(cfg_mgr->active->internal->tid_req_timeout, &ts_abort)) {
638     tr_notice("tr_tids_req_handler: unable to read clock for timeout.");
639     retval=-1;
640     goto cleanup;
641   }
642
643   /* wait for responses */
644   tr_debug("tr_tids_req_handler: waiting for response(s).");
645   n_responses=0;
646   n_failed=0;
647   while (((n_responses+n_failed)<n_aaa) &&
648          (NULL!=(msg=tr_mq_pop(mq, &ts_abort)))) {
649     /* process message */
650     if (0==strcmp(tr_mq_msg_get_message(msg), TR_TID_MQMSG_SUCCESS)) {
651       payload=talloc_get_type_abort(tr_mq_msg_get_payload(msg), TR_RESP_COOKIE);
652       talloc_steal(tmp_ctx, payload); /* put this back in our context */
653       aaa_resp[payload->thread_id]=payload->resp; /* save pointers to these */
654
655       if (payload->resp->result==TID_SUCCESS) {
656         tr_tids_merge_resps(resp, payload->resp);
657         n_responses++;
658       } else {
659         n_failed++;
660         tr_notice("tr_tids_req_handler: TID error received from AAA server %d: %.*s",
661                   payload->thread_id,
662                   payload->resp->err_msg->len,
663                   payload->resp->err_msg->buf);
664       }
665     } else if (0==strcmp(tr_mq_msg_get_message(msg), TR_TID_MQMSG_FAILURE)) {
666       /* failure */
667       n_failed++;
668       payload=talloc_get_type(tr_mq_msg_get_payload(msg), TR_RESP_COOKIE);
669       if (payload!=NULL) 
670         talloc_steal(tmp_ctx, payload); /* put this back in our context */
671       else {
672         /* this means the thread was unable to allocate a response cookie, and we thus cannot determine which thread it was. This is bad and should never happen in a working system.. Give up. */
673         tr_notice("tr_tids_req_handler: TID request thread sent invalid reply. Aborting!");
674         retval=-1;
675         goto cleanup;
676       }
677       tr_notice("tr_tids_req_handler: TID request for AAA server %d failed.",
678                 payload->thread_id);
679     } else {
680       /* unexpected message */
681       tr_err("tr_tids_req_handler: Unexpected message received. Aborting!");
682       retval=-1;
683       goto cleanup;
684     }
685     
686     /* Set the cookie pointer to NULL so we know we've dealt with this one. The
687      * cookie itself is in our tmp_ctx, which we'll free before exiting. Let it hang
688      * around in case we are still using pointers to elements of the cookie. */
689     aaa_cookie[payload->thread_id]=NULL;
690
691     tr_mq_msg_free(msg);
692
693     /* check whether we've received enough responses to exit */
694     if ((idp_shared && (n_responses>0)) ||
695         (resp_frac_denom*n_responses>=resp_frac_numer*n_aaa))
696       break;
697   }
698
699   tr_debug("tr_tids_req_handler: done waiting for responses. %d responses, %d failures.",
700            n_responses, n_failed);
701   /* Inform any remaining threads that we will no longer handle their responses. */
702   for (ii=0; ii<n_aaa; ii++) {
703     if (aaa_cookie[ii]!=NULL) {
704       if (0!=tr_tids_fwd_get_mutex(aaa_cookie[ii]))
705         tr_notice("tr_tids_req_handler: unable to get mutex for AAA thread %d.", ii);
706
707       aaa_cookie[ii]->mq=NULL; /* threads will not try to respond through a null mq */
708
709       if (0!=tr_tids_fwd_release_mutex(aaa_cookie[ii]))
710         tr_notice("tr_tids_req_handler: unable to release mutex for AAA thread %d.", ii);
711     }
712   }
713
714   /* Now all threads have either replied (and aaa_cookie[ii] is null) or have been told not to
715    * reply (by setting their mq pointer to null). However, some may have responded by placing
716    * a message on the mq after we last checked but before we set their mq pointer to null. These
717    * will not know that we gave up on them, so we must free their cookies for them. We can just
718    * go through any remaining messages on the mq to identify these threads. By putting them in
719    * our context instead of freeing them directly, we ensure we don't accidentally invalidate
720    * any of our own pointers into the structure before this function exits. */
721   while (NULL!=(msg=tr_mq_pop(mq, NULL))) {
722     payload=(TR_RESP_COOKIE *)tr_mq_msg_get_payload(msg);
723     if (aaa_cookie[payload->thread_id]!=NULL)
724       talloc_steal(tmp_ctx, aaa_cookie[payload->thread_id]);
725
726     tr_mq_msg_free(msg);
727   }
728
729   if (n_responses==0) {
730     /* No requests succeeded, so this will be an error */
731     retval = -1;
732
733     /* If we got any error responses, send an arbitrarily chosen one. */
734     for (ii=0; ii<n_aaa; ii++) {
735       if (aaa_resp[ii] != NULL) {
736         tid_resp_cpy(resp, aaa_resp[ii]);
737         goto cleanup;
738       }
739     }
740     /* No error responses at all, so generate our own error. */
741     tid_resp_set_err_msg(resp, tr_new_name("Unable to contact AAA server(s)."));
742     goto cleanup;
743   }
744
745   /* success! */
746   retval=0;
747     
748 cleanup:
749   talloc_free(tmp_ctx);
750   return retval;
751 }
752
753 static int tr_tids_gss_handler(gss_name_t client_name, TR_NAME *gss_name,
754                                void *data)
755 {
756   struct tr_tids_event_cookie *cookie=talloc_get_type_abort(data, struct tr_tids_event_cookie);
757   TIDS_INSTANCE *tids = cookie->tids;
758   TR_CFG_MGR *cfg_mgr = cookie->cfg_mgr;
759
760   if ((!client_name) || (!gss_name) || (!tids) || (!cfg_mgr)) {
761     tr_debug("tr_tidc_gss_handler: Bad parameters.");
762     return -1;
763   }
764
765   /* Ensure at least one client exists using this GSS name */
766   if (NULL == tr_rp_client_lookup(cfg_mgr->active->rp_clients, gss_name)) {
767     tr_debug("tr_tids_gss_handler: Unknown GSS name %.*s", gss_name->len, gss_name->buf);
768     return -1;
769   }
770
771   /* Store the GSS name */
772   tids->gss_name = tr_dup_name(gss_name);
773   tr_debug("Client's GSS Name: %.*s", gss_name->len, gss_name->buf);
774
775   return 0;
776 }
777
778
779 /***** TIDS event handling *****/
780
781 /* called when a connection to the TIDS port is received */
782 static void tr_tids_event_cb(int listener, short event, void *arg)
783 {
784   TIDS_INSTANCE *tids = talloc_get_type_abort(arg, TIDS_INSTANCE);
785
786   if (0==(event & EV_READ))
787     tr_debug("tr_tids_event_cb: unexpected event on TIDS socket (event=0x%X)", event);
788   else 
789     tids_accept(tids, listener);
790 }
791
792 /* called when it's time to sweep for completed TID child processes */
793 static void tr_tids_sweep_cb(int listener, short event, void *arg)
794 {
795   TIDS_INSTANCE *tids = talloc_get_type_abort(arg, TIDS_INSTANCE);
796
797   if (0==(event & EV_TIMEOUT))
798     tr_debug("tr_tids_event_cb: unexpected event on TID process sweep timer (event=0x%X)", event);
799   else
800     tids_sweep_procs(tids);
801 }
802
803 /* Configure the tids instance and set up its event handlers.
804  * Returns 0 on success, nonzero on failure. Fills in
805  * *tids_event (which should be allocated by caller). */
806 int tr_tids_event_init(struct event_base *base, TIDS_INSTANCE *tids, TR_CFG_MGR *cfg_mgr, TRPS_INSTANCE *trps,
807                        struct tr_socket_event *tids_ev, struct event **sweep_ev)
808 {
809   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
810   struct tr_tids_event_cookie *cookie=NULL;
811   struct timeval sweep_interval;
812   int retval=0;
813   int ii=0;
814
815   if (tids_ev == NULL) {
816     tr_debug("tr_tids_event_init: Null tids_ev.");
817     retval=1;
818     goto cleanup;
819   }
820
821   if (sweep_ev == NULL) {
822     tr_debug("tr_tids_event_init: Null sweep_ev.");
823     retval = 1;
824     goto cleanup;
825   }
826
827   /* Create the cookie for callbacks. We'll put it in the tids context, so it will
828    * be cleaned up when tids is freed by talloc_free. */
829   cookie=talloc(tmp_ctx, struct tr_tids_event_cookie);
830   if (cookie == NULL) {
831     tr_debug("tr_tids_event_init: Unable to allocate cookie.");
832     retval=1;
833     goto cleanup;
834   }
835   cookie->tids=tids;
836   cookie->cfg_mgr=cfg_mgr;
837   cookie->trps=trps;
838   talloc_steal(tids, cookie);
839
840   /* get a tids listener */
841   tids_ev->n_sock_fd = (int)tids_get_listener(tids,
842                                               tr_tids_req_handler,
843                                               tr_tids_gss_handler,
844                                               cfg_mgr->active->internal->hostname,
845                                               cfg_mgr->active->internal->tids_port,
846                                               (void *)cookie,
847                                               tids_ev->sock_fd,
848                                               TR_MAX_SOCKETS);
849   if (tids_ev->n_sock_fd==0) {
850     tr_crit("Error opening TID server socket.");
851     retval=1;
852     goto cleanup;
853   }
854
855   /* Set up listener events */
856   for (ii=0; ii<tids_ev->n_sock_fd; ii++) {
857     tids_ev->ev[ii]=event_new(base,
858                               tids_ev->sock_fd[ii],
859                               EV_READ|EV_PERSIST,
860                               tr_tids_event_cb,
861                               (void *)tids);
862     event_add(tids_ev->ev[ii], NULL);
863   }
864
865   /* Set up a periodic check for completed TID handler processes */
866   *sweep_ev = event_new(base, -1, EV_TIMEOUT|EV_PERSIST, tr_tids_sweep_cb, tids);
867   sweep_interval.tv_sec = 10;
868   sweep_interval.tv_usec = 0;
869   event_add(*sweep_ev, &sweep_interval);
870
871 cleanup:
872   talloc_free(tmp_ctx);
873   return retval;
874 }