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