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