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