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