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