Merge pull request #76 from painless-security/jennifer/trpc_deadlock
[trust_router.git] / trp / trps.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 <fcntl.h>
36 #include <talloc.h>
37 #include <errno.h>
38 #include <unistd.h>
39 #include <sys/time.h>
40 #include <glib.h>
41 #include <string.h>
42 #include <poll.h> // for nfds_t
43
44 #include <gsscon.h>
45 #include <tr_comm.h>
46 #include <tr_apc.h>
47 #include <tr_rp.h>
48 #include <tr_name_internal.h>
49 #include <trp_route.h>
50 #include <trp_internal.h>
51 #include <tr_gss_names.h>
52 #include <trp_peer.h>
53 #include <trp_ptable.h>
54 #include <trp_rtable.h>
55 #include <tr_debug.h>
56 #include <tr_util.h>
57 #include <tr_socket.h>
58
59 static int trps_destructor(void *object)
60 {
61   TRPS_INSTANCE *trps=talloc_get_type_abort(object, TRPS_INSTANCE);
62   if (trps->rtable!=NULL)
63     trp_rtable_free(trps->rtable);
64   return 0;
65 }
66
67 TRPS_INSTANCE *trps_new (TALLOC_CTX *mem_ctx)
68 {
69   TRPS_INSTANCE *trps=talloc(mem_ctx, TRPS_INSTANCE);
70   if (trps!=NULL)  {
71     trps->hostname=NULL;
72     trps->port=0;
73     trps->cookie=NULL;
74     trps->conn=NULL;
75     trps->trpc=NULL;
76     trps->update_interval=(struct timeval){0,0};
77     trps->sweep_interval=(struct timeval){0,0};
78     trps->ptable=NULL;
79
80     trps->mq=tr_mq_new(trps);
81     if (trps->mq==NULL) {
82       /* failed to allocate mq */
83       talloc_free(trps);
84       return NULL;
85     }
86
87     trps->rtable=NULL;
88     if (trps_init_rtable(trps) != TRP_SUCCESS) {
89       /* failed to allocate rtable */
90       talloc_free(trps);
91       return NULL;
92     }
93
94     talloc_set_destructor((void *)trps, trps_destructor);
95   }
96   return trps;
97 }
98
99 /* create a new route table, first discarding an old one if necessary */
100 TRP_RC trps_init_rtable(TRPS_INSTANCE *trps)
101 {
102   if (trps->rtable != NULL) {
103     trp_rtable_free(trps->rtable);
104     trps->rtable=NULL;
105   }
106
107   trps->rtable=trp_rtable_new();
108   if (trps->rtable==NULL) {
109     return TRP_NOMEM;
110   }
111   return TRP_SUCCESS;
112 }
113
114 void trps_clear_rtable(TRPS_INSTANCE *trps)
115 {
116   trp_rtable_clear(trps->rtable);
117 }
118
119 void trps_free (TRPS_INSTANCE *trps)
120 {
121   if (trps!=NULL)
122     talloc_free(trps);
123 }
124
125 TR_MQ_MSG *trps_mq_pop(TRPS_INSTANCE *trps)
126 {
127   return tr_mq_pop(trps->mq, 0);
128 }
129
130 void trps_mq_add(TRPS_INSTANCE *trps, TR_MQ_MSG *msg)
131 {
132   tr_mq_add(trps->mq, msg);
133 }
134
135 unsigned int trps_get_connect_interval(TRPS_INSTANCE *trps)
136 {
137   return trps->connect_interval.tv_sec;
138 }
139
140 void trps_set_connect_interval(TRPS_INSTANCE *trps, unsigned int interval)
141 {
142   trps->connect_interval.tv_sec=interval;
143   trps->connect_interval.tv_usec=0;
144 }
145
146 unsigned int trps_get_update_interval(TRPS_INSTANCE *trps)
147 {
148   return trps->update_interval.tv_sec;
149 }
150
151 void trps_set_update_interval(TRPS_INSTANCE *trps, unsigned int interval)
152 {
153   trps->update_interval.tv_sec=interval;
154   trps->update_interval.tv_usec=0;
155 }
156
157 unsigned int trps_get_sweep_interval(TRPS_INSTANCE *trps)
158 {
159   return trps->sweep_interval.tv_sec;
160 }
161
162 void trps_set_sweep_interval(TRPS_INSTANCE *trps, unsigned int interval)
163 {
164   trps->sweep_interval.tv_sec=interval;
165   trps->sweep_interval.tv_usec=0;
166 }
167
168 void trps_set_ctable(TRPS_INSTANCE *trps, TR_COMM_TABLE *comm)
169 {
170   trps->ctable=comm;
171 }
172
173 void trps_set_ptable(TRPS_INSTANCE *trps, TRP_PTABLE *ptable)
174 {
175   if (trps->ptable!=NULL)
176     trp_ptable_free(trps->ptable);
177   trps->ptable=ptable;
178 }
179
180 void trps_set_peer_status_callback(TRPS_INSTANCE *trps, void (*cb)(TRP_PEER *, void *), void *cookie)
181 {
182   TRP_PTABLE_ITER *iter=NULL;
183   TRP_PEER *peer=NULL;
184   if (trps->ptable==NULL)
185     return;
186
187   iter=trp_ptable_iter_new(NULL);
188   for (peer=trp_ptable_iter_first(iter, trps->ptable); peer!=NULL; peer=trp_ptable_iter_next(iter))
189     trp_peer_set_conn_status_cb(peer, cb, cookie);
190   trp_ptable_iter_free(iter);
191 }
192
193 /* Get the label peers will know us by - needs to match trp_peer_get_label() output.
194  * There is no get, only dup, because we don't store the label except when requested. */
195 TR_NAME *trps_dup_label(TRPS_INSTANCE *trps)
196 {
197   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
198   TR_NAME *label=NULL;
199   char *s=talloc_asprintf(tmp_ctx, "%s:%u", trps->hostname, trps->port);
200   if (s==NULL)
201     goto cleanup;
202   label=tr_new_name(s);
203
204 cleanup:
205   talloc_free(tmp_ctx);
206   return label;
207 }
208
209 TRPC_INSTANCE *trps_find_trpc(TRPS_INSTANCE *trps, TRP_PEER *peer)
210 {
211   TRPC_INSTANCE *cur=NULL;
212   TR_NAME *name=NULL;
213   TR_NAME *peer_servicename=trp_peer_get_servicename(peer);
214
215   for (cur=trps->trpc; cur!=NULL; cur=trpc_get_next(cur)) {
216     name=trpc_get_gssname(cur);
217     if ((name!=NULL) && (0==tr_name_cmp(peer_servicename, name))) {
218       break;
219     }
220   }
221   return cur;
222 }
223
224 void trps_add_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *new)
225 {
226   if (trps->conn==NULL)
227     trps->conn=new;
228   else
229     trp_connection_append(trps->conn, new);
230
231   talloc_steal(trps, new);
232 }
233
234 /* ok to call more than once; guarantees connection no longer in the list.
235  * Caller is responsible for freeing the removed element afterwards.  */
236 void trps_remove_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *remove)
237 {
238   trps->conn=trp_connection_remove(trps->conn, remove);
239 }
240
241 void trps_add_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *trpc)
242 {
243   if (trps->trpc==NULL)
244     trps->trpc=trpc;
245   else
246     trpc_append(trps->trpc, trpc);
247
248   talloc_steal(trps, trpc);
249 }
250
251 /* ok to call more than once; guarantees trpc no longer in the list.
252  * Caller is responsible for freeing the removed element afterwards.  */
253 void trps_remove_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *remove)
254 {
255   trps->trpc=trpc_remove(trps->trpc, remove);
256 }
257
258 TRP_RC trps_send_msg(TRPS_INSTANCE *trps, TRP_PEER *peer, const char *msg)
259 {
260   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
261   TR_MQ_MSG *mq_msg=NULL;
262   char *msg_dup=NULL;
263   TRP_RC rc=TRP_ERROR;
264   TRPC_INSTANCE *trpc=NULL;
265
266   /* get the connection for this peer */
267   trpc=trps_find_trpc(trps, peer);
268   /* The peer connection (trpc) usually exists even if the connection is down.
269    * We will queue messages even if the connection is down. To prevent this from
270    * endlessly increasing the size of the queue, the trpc handler needs to clear
271    * its queue periodically, even if it is unable to send the messages
272    */
273   if (trpc==NULL) {
274     tr_warning("trps_send_msg: skipping message queued for missing TRP client entry.");
275   } else {
276     mq_msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_SEND, TR_MQ_PRIO_NORMAL);
277     msg_dup=talloc_strdup(mq_msg, msg); /* get local copy in mq_msg context */
278     tr_mq_msg_set_payload(mq_msg, msg_dup, NULL); /* no need for a free() func */
279     trpc_mq_add(trpc, mq_msg);
280     rc=TRP_SUCCESS;
281   }
282   talloc_free(tmp_ctx);
283   return rc;
284 }
285
286 /* get the currently selected route if available */
287 TRP_ROUTE *trps_get_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
288 {
289   return trp_rtable_get_entry(trps->rtable, comm, realm, peer);
290 }
291
292 TRP_ROUTE *trps_get_selected_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
293 {
294   tr_debug("trps_get_selected_route: entered. trps=%p, comm=%p, realm=%p", trps, comm, realm);
295   return trp_rtable_get_selected_entry(trps->rtable, comm, realm);
296 }
297
298 /* copy the result if you want to keep it */
299 TR_NAME *trps_get_next_hop(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
300 {
301   TRP_ROUTE *route=trps_get_selected_route(trps, comm, realm);
302   if (route==NULL)
303     return NULL;
304
305   return trp_route_get_next_hop(route);
306 }
307
308
309 /* mark a route as retracted */
310 static void trps_retract_route(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
311 {
312   trp_route_set_metric(entry, TRP_METRIC_INFINITY);
313   trp_route_set_triggered(entry, 1);
314 }
315
316 /* is this route retracted? */
317 static int trps_route_retracted(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
318 {
319   return (trp_metric_is_infinite(trp_route_get_metric(entry)));
320 }
321
322 static TRP_RC trps_read_message(TRPS_INSTANCE *trps, TRP_CONNECTION *conn, TR_MSG **msg)
323 {
324   int err=0;
325   char *buf=NULL;
326   size_t buflen = 0;
327   TRP_PEER *peer=NULL; /* entry in the peer table */
328   TR_NAME *conn_peer=NULL; /* name from the TRP_CONN, which comes from the gss context */
329
330   tr_debug("trps_read_message: started");
331   if (err = gsscon_read_encrypted_token(trp_connection_get_fd(conn),
332                                        *(trp_connection_get_gssctx(conn)), 
333                                        &buf,
334                                        &buflen)) {
335     tr_debug("trps_read_message: error");
336     if (buf)
337       free(buf);
338     return TRP_ERROR;
339   }
340
341   tr_debug("trps_read_message: message received, %u bytes.", (unsigned) buflen);
342   tr_debug("trps_read_message: %.*s", buflen, buf);
343
344   *msg= tr_msg_decode(NULL, buf, buflen);
345   free(buf);
346   if (*msg==NULL)
347     return TRP_NOPARSE;
348
349   conn_peer=trp_connection_get_peer(conn);
350   if (conn_peer==NULL) {
351     tr_err("trps_read_message: connection has no peer name");
352     return TRP_ERROR;
353   }
354
355   peer=trps_get_peer_by_gssname(trps, conn_peer);
356   if (peer==NULL) {
357     tr_err("trps_read_message: could not find peer with gssname=%s", trp_connection_get_gssname(conn));
358     return TRP_ERROR;
359   }
360
361   /* verify we received a message we support, otherwise drop it now */
362   switch (tr_msg_get_msg_type(*msg)) {
363   case TRP_UPDATE:
364     trp_upd_set_peer(tr_msg_get_trp_upd(*msg), tr_dup_name(conn_peer));
365     trp_upd_set_next_hop(tr_msg_get_trp_upd(*msg), trp_peer_get_server(peer), 0); /* TODO: 0 should be the configured TID port */
366     /* update provenance if necessary */
367     trp_upd_add_to_provenance(tr_msg_get_trp_upd(*msg), trp_peer_get_label(peer));
368     break;
369
370   case TRP_REQUEST:
371     trp_req_set_peer(tr_msg_get_trp_req(*msg), tr_dup_name(conn_peer));
372     break;
373
374   default:
375     tr_debug("trps_read_message: received unsupported message from %.*s", conn_peer->len, conn_peer->buf);
376     tr_msg_free_decoded(*msg);
377     *msg=NULL;
378     return TRP_UNSUPPORTED;
379   }
380   
381   return TRP_SUCCESS;
382 }
383
384 int trps_get_listener(TRPS_INSTANCE *trps,
385                       TRPS_MSG_FUNC msg_handler,
386                       TRP_AUTH_FUNC auth_handler,
387                       const char *hostname,
388                       unsigned int port,
389                       void *cookie,
390                       int *fd_out,
391                       size_t max_fd)
392 {
393   nfds_t n_fd=0;
394   nfds_t ii=0;
395
396   n_fd = tr_sock_listen_all(port, fd_out, max_fd);
397
398   if (n_fd == 0)
399     tr_err("trps_get_listener: Error opening port %d.");
400   else {
401     /* opening port succeeded */
402     tr_info("trps_get_listener: Opened port %d.", port);
403     
404     /* make the sockets non-blocking */
405     for (ii=0; ii<n_fd; ii++) {
406       if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
407         tr_err("trps_get_listener: Error setting O_NONBLOCK.");
408         for (ii=0; ii<n_fd; ii++) {
409           close(fd_out[ii]);
410           fd_out[ii]=-1;
411         }
412         n_fd = 0;
413         break;
414       }
415     }
416   }
417
418   if (n_fd > 0) {
419     /* store the caller's request handler & cookie */
420     trps->msg_handler = msg_handler;
421     trps->auth_handler = auth_handler;
422     trps->hostname = talloc_strdup(trps, hostname);
423     trps->port = port;
424     trps->cookie = cookie;
425   }
426
427   return (int) n_fd;
428 }
429
430 TRP_RC trps_authorize_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
431 {
432   /* try to establish a GSS context */
433   if (0!=trp_connection_auth(conn, trps->auth_handler, trps->cookie)) {
434     tr_notice("trps_authorize_connection: failed to authorize connection");
435     trp_connection_close(conn);
436     return TRP_ERROR;
437   }
438   tr_notice("trps_authorize_connection: authorized connection");
439   return TRP_SUCCESS;
440 }
441
442 void trps_handle_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
443 {
444   TR_MSG *msg=NULL;
445   TRP_RC rc=TRP_ERROR;
446
447   /* loop as long as the connection exists */
448   while (trp_connection_get_status(conn)==TRP_CONNECTION_UP) {
449     rc=trps_read_message(trps, conn, &msg);
450     switch(rc) {
451     case TRP_SUCCESS:
452       trps->msg_handler(trps, conn, msg); /* send the TR_MSG off to the callback */
453       break;
454
455     case TRP_ERROR:
456       trp_connection_close(conn);
457       break;
458
459     default:
460       tr_debug("trps_handle_connection: trps_read_message failed (%d)", rc);
461     }
462   }
463
464   tr_debug("trps_handle_connection: connection closed.");
465 }
466
467 /* TODO: check realm/comm, now part of the update instead of inforec */
468 static TRP_RC trps_validate_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
469 {
470   if (upd==NULL) {
471     tr_notice("trps_validate_update: null TRP update.");
472     return TRP_BADARG;
473   }
474
475   if (trp_upd_get_realm(upd)==NULL) {
476     tr_notice("trps_validate_update: received TRP update without realm.");
477     return TRP_ERROR;
478   }
479
480   if (trp_upd_get_comm(upd)==NULL) {
481     tr_notice("trps_validate_update: received TRP update without community.");
482     return TRP_ERROR;
483   }
484
485   if (trp_upd_get_inforec(upd)==NULL) {
486     tr_notice("trps_validate_update: received TRP update with no info records.");
487     return TRP_ERROR;
488   }
489
490   if (trp_upd_get_peer(upd)==NULL) {
491     tr_notice("trps_validate_update: received TRP update without origin peer information.");
492     return TRP_ERROR;
493   }
494
495   
496   return TRP_SUCCESS;
497 }
498
499 /* ensure that the update could be accepted if feasible */
500 static TRP_RC trps_validate_inforec(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
501 {
502   switch(trp_inforec_get_type(rec)) {
503   case TRP_INFOREC_TYPE_ROUTE:
504     if ((trp_inforec_get_trust_router(rec)==NULL)
505        || (trp_inforec_get_next_hop(rec)==NULL)) {
506       tr_debug("trps_validate_inforec: missing record info.");
507       return TRP_ERROR;
508     }
509
510     /* check for valid metric */
511     if (trp_metric_is_invalid(trp_inforec_get_metric(rec))) {
512       tr_debug("trps_validate_inforec: invalid metric (%u).", trp_inforec_get_metric(rec));
513       return TRP_ERROR;
514     }
515
516     /* check for valid interval */
517     if (trp_inforec_get_interval(rec)==TRP_INTERVAL_INVALID) {
518       tr_debug("trps_validate_inforec: invalid interval.");
519       return TRP_ERROR;
520     }
521     break;
522
523   case TRP_INFOREC_TYPE_COMMUNITY:
524     /* TODO: validate community updates */
525     break;
526     
527   default:
528     tr_notice("trps_validate_inforec: unsupported record type.");
529     return TRP_UNSUPPORTED;
530   }
531
532   return TRP_SUCCESS;
533 }
534
535 /* link cost to a peer */
536 static unsigned int trps_cost(TRPS_INSTANCE *trps, TR_NAME *peer)
537 {
538   return 1;
539 }
540
541 static unsigned int trps_advertised_metric(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
542 {
543   TRP_ROUTE *entry=trp_rtable_get_entry(trps->rtable, comm, realm, peer);
544   if (entry==NULL)
545     return TRP_METRIC_INFINITY;
546   return trp_route_get_metric(entry) + trps_cost(trps, peer);
547 }
548
549 static int trps_check_feasibility(TRPS_INSTANCE *trps, TR_NAME *realm, TR_NAME *comm, TRP_INFOREC *rec)
550 {
551   unsigned int rec_metric=trp_inforec_get_metric(rec);
552   unsigned int new_metric=0;
553   unsigned int current_metric=0;
554   TR_NAME *next_hop=NULL;
555
556   /* we check these in the validation stage, but just in case... */
557   if (trp_metric_is_invalid(rec_metric))
558     return 0;
559
560   /* retractions (aka infinite metrics) are always feasible */
561   if (trp_metric_is_infinite(rec_metric))
562     return 1;
563
564   /* updates from our current next hop are always feasible*/
565   next_hop=trps_get_next_hop(trps, comm, realm);
566   if ((next_hop!=NULL)
567      && (0==tr_name_cmp(next_hop,trp_inforec_get_next_hop(rec)))) {
568     return 1;
569   }
570     
571
572   /* compare the existing metric we advertise to what we would advertise
573    * if we accept this update */
574   current_metric=trps_advertised_metric(trps, comm, realm, trp_inforec_get_next_hop(rec));
575   new_metric=rec_metric + trps_cost(trps, trp_inforec_get_next_hop(rec));
576   if (new_metric <= current_metric)
577     return 1;
578   else
579     return 0;
580 }
581
582 /* uses memory pointed to by *ts, also returns that value. On error, its contents are {0,0} */
583 static struct timespec *trps_compute_expiry(TRPS_INSTANCE *trps, unsigned int interval, struct timespec *ts)
584 {
585   const unsigned int small_factor=3; /* how many intervals we wait before expiring */
586   if (0!=clock_gettime(TRP_CLOCK, ts)) {
587     tr_err("trps_compute_expiry: could not read realtime clock.");
588     ts->tv_sec=0;
589     ts->tv_nsec=0;
590   }
591   tr_debug("trps_compute_expiry: tv_sec=%u, interval=%u, small_factor*interval=%u", ts->tv_sec, interval, small_factor*interval);
592   ts->tv_sec += small_factor*interval;
593   return ts;
594 }
595
596 static TRP_RC trps_accept_update(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
597 {
598   TRP_ROUTE *entry=NULL;
599
600   entry=trp_rtable_get_entry(trps->rtable,
601                              trp_upd_get_comm(upd),
602                              trp_upd_get_realm(upd),
603                              trp_inforec_get_next_hop(rec));
604   if (entry==NULL) {
605     entry=trp_route_new(NULL);
606     if (entry==NULL) {
607       tr_err("trps_accept_update: unable to allocate new entry.");
608       return TRP_NOMEM;
609     }
610
611     trp_route_set_comm(entry, trp_upd_dup_comm(upd));
612     trp_route_set_realm(entry, trp_upd_dup_realm(upd));
613     trp_route_set_peer(entry, trp_upd_dup_peer(upd));
614     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec));
615     trp_route_set_next_hop(entry, trp_inforec_dup_next_hop(rec));
616     /* TODO: pass next hop port (now defaults to TID_PORT) --jlr */
617     if ((trp_route_get_comm(entry)==NULL)
618        ||(trp_route_get_realm(entry)==NULL)
619        ||(trp_route_get_peer(entry)==NULL)
620        ||(trp_route_get_trust_router(entry)==NULL)
621        ||(trp_route_get_next_hop(entry)==NULL)) {
622       /* at least one field could not be allocated */
623       tr_err("trps_accept_update: unable to allocate all fields for entry.");
624       trp_route_free(entry);
625       return TRP_NOMEM;
626     }
627     trp_rtable_add(trps->rtable, entry);
628   }
629
630   /* We now have an entry in the table, whether it's new or not. Update metric and expiry, unless
631    * the metric is infinity. An infinite metric can only occur here if we just retracted an existing
632    * route (we never accept retractions as new routes), so there is no risk of leaving the expiry
633    * time unset on a new route entry. */
634   tr_debug("trps_accept_update: accepting route update.");
635   trp_route_set_metric(entry, trp_inforec_get_metric(rec));
636   trp_route_set_interval(entry, trp_inforec_get_interval(rec));
637
638   /* check whether the trust router has changed */
639   if (0!=tr_name_cmp(trp_route_get_trust_router(entry),
640                      trp_inforec_get_trust_router(rec))) {
641     /* The name changed. Set this route as triggered. */
642     tr_debug("trps_accept_update: trust router for route changed.");
643     trp_route_set_triggered(entry, 1);
644     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec)); /* frees old name */
645   }
646   if (!trps_route_retracted(trps, entry)) {
647     tr_debug("trps_accept_update: route not retracted, setting expiry timer.");
648     trp_route_set_expiry(entry, trps_compute_expiry(trps,
649                                                      trp_route_get_interval(entry),
650                                                      trp_route_get_expiry(entry)));
651   }
652   return TRP_SUCCESS;
653 }
654
655
656 static TRP_RC trps_handle_inforec_route(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
657 {
658   TRP_ROUTE *route=NULL;
659   TR_COMM *comm = NULL;
660   unsigned int feas=0;
661
662   /* determine feasibility */
663   feas=trps_check_feasibility(trps, trp_upd_get_realm(upd), trp_upd_get_comm(upd), rec);
664   tr_debug("trps_handle_update: record feasibility=%d", feas);
665
666   /* verify that the community is an APC */
667   comm = tr_comm_table_find_comm(trps->ctable, trp_upd_get_comm(upd));
668   if (comm == NULL) {
669     /* We don't know this community. Reject the route. */
670     tr_debug("trps_handle_updates: community %.*s unknown, ignoring route for %.*s",
671              trp_upd_get_comm(upd)->len, trp_upd_get_comm(upd)->buf,
672              trp_upd_get_realm(upd)->len, trp_upd_get_realm(upd)->buf);
673   } else if (tr_comm_get_type(comm) != TR_COMM_APC) {
674     /* The community in a route request *must* be an APC. This was not - ignore it. */
675     tr_debug("trps_handle_updates: community %.*s is not an APC, ignoring route for %.*s",
676              trp_upd_get_comm(upd)->len, trp_upd_get_comm(upd)->buf,
677              trp_upd_get_realm(upd)->len, trp_upd_get_realm(upd)->buf);
678   } else {
679     /* do we have an existing route? */
680     route=trps_get_route(trps,
681                          trp_upd_get_comm(upd),
682                          trp_upd_get_realm(upd),
683                          trp_upd_get_peer(upd));
684     if (route!=NULL) {
685       /* there was a route table entry already */
686       tr_debug("trps_handle_updates: route entry already exists.");
687       if (feas) {
688         /* Update is feasible. Accept it. */
689         trps_accept_update(trps, upd, rec);
690       } else {
691         /* Update is infeasible. Ignore it unless the trust router has changed. */
692         if (0!=tr_name_cmp(trp_route_get_trust_router(route),
693                            trp_inforec_get_trust_router(rec))) {
694           /* the trust router associated with the route has changed, treat update as a retraction */
695           trps_retract_route(trps, route);
696         }
697       }
698     } else {
699       /* No existing route table entry. Ignore it unless it is feasible and not a retraction. */
700       tr_debug("trps_handle_update: no route entry exists yet.");
701       if (feas && trp_metric_is_finite(trp_inforec_get_metric(rec)))
702         trps_accept_update(trps, upd, rec);
703     }
704   }
705
706   return TRP_SUCCESS;
707 }
708
709 static int trps_name_in_provenance(TR_NAME *name, json_t *prov)
710 {
711   size_t ii=0;
712   TR_NAME *this_name=NULL;
713   const char *s=NULL;
714
715   if (prov==NULL)
716     return 0; /* no provenance list, so it has no names in it */
717
718   /* now check to see if name is in the provenance */
719   for (ii=0; ii<json_array_size(prov); ii++) {
720     s=json_string_value(json_array_get(prov, ii));
721     if (s==NULL) {
722       tr_debug("trps_name_in_provenance: empty entry in provenance list.");
723       continue;
724     }
725
726     this_name=tr_new_name(s);
727     if (this_name==NULL) {
728       tr_debug("trps_name_in_provenance: unable to allocate name.");
729       return -1;
730     }
731     if (0==tr_name_cmp(name, this_name)) {
732       tr_free_name(this_name);
733       return 1;
734     }
735     tr_free_name(this_name);
736   }
737   return 0;
738 }
739
740 static TR_COMM *trps_create_new_comm(TALLOC_CTX *mem_ctx, TR_NAME *comm_id, TRP_INFOREC *rec)
741 {
742   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
743   TR_COMM *comm=tr_comm_new(tmp_ctx);
744   
745   if (comm==NULL) {
746     tr_debug("trps_create_new_comm: unable to allocate new community.");
747     goto cleanup;
748   }
749   /* fill in the community with info */
750   tr_comm_set_id(comm, tr_dup_name(comm_id));
751   if (tr_comm_get_id(comm)==NULL) {
752     tr_debug("trps_create_new_comm: unable to allocate community name.");
753     comm=NULL;
754     goto cleanup;
755   }
756   tr_comm_set_type(comm, trp_inforec_get_comm_type(rec));
757   if (trp_inforec_get_apcs(rec)!=NULL) {
758     tr_comm_set_apcs(comm, tr_apc_dup(tmp_ctx, trp_inforec_get_apcs(rec)));
759     if (tr_comm_get_apcs(comm)==NULL) {
760       tr_debug("trps_create_new_comm: unable to allocate APC list.");
761       comm=NULL;
762       goto cleanup;
763     }
764   }
765   if (trp_inforec_get_owner_realm(rec)!=NULL) {
766     tr_comm_set_owner_realm(comm, tr_dup_name(trp_inforec_get_owner_realm(rec)));
767     if (tr_comm_get_owner_realm(comm)==NULL) {
768       tr_debug("trps_create_new_comm: unable to allocate owner realm name.");
769       comm=NULL;
770       goto cleanup;
771     }
772   }
773   if (trp_inforec_get_owner_contact(rec)!=NULL) {
774     tr_comm_set_owner_contact(comm, tr_dup_name(trp_inforec_get_owner_contact(rec)));
775     if (tr_comm_get_owner_contact(comm)==NULL) {
776       tr_debug("trps_create_new_comm: unable to allocate owner contact.");
777       comm=NULL;
778       goto cleanup;
779     }
780   }
781   comm->expiration_interval=trp_inforec_get_exp_interval(rec);
782   talloc_steal(mem_ctx, comm);
783   
784 cleanup:
785   talloc_free(tmp_ctx);
786   return comm;
787 }
788
789 static TR_RP_REALM *trps_create_new_rp_realm(TALLOC_CTX *mem_ctx, TR_NAME *comm, TR_NAME *realm_id, TRP_INFOREC *rec)
790 {
791   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
792   TR_RP_REALM *rp=tr_rp_realm_new(tmp_ctx);
793   
794   if (rp==NULL) {
795     tr_debug("trps_create_new_rp_realm: unable to allocate new realm.");
796     goto cleanup;
797   }
798   /* fill in the realm */
799   tr_rp_realm_set_id(rp, tr_dup_name(realm_id));
800   if (tr_rp_realm_get_id(rp)==NULL) {
801     tr_debug("trps_create_new_rp_realm: unable to allocate realm name.");
802     rp=NULL;
803     goto cleanup;
804   }
805   talloc_steal(mem_ctx, rp);
806   
807 cleanup:
808   talloc_free(tmp_ctx);
809   return rp;
810 }
811
812 static TR_IDP_REALM *trps_create_new_idp_realm(TALLOC_CTX *mem_ctx,
813                                                TR_NAME *comm_id,
814                                                TR_NAME *realm_id,
815                                                TRP_INFOREC *rec)
816 {
817   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
818   TR_IDP_REALM *idp=tr_idp_realm_new(tmp_ctx);
819   TR_APC *realm_apcs = NULL;
820
821   if (idp==NULL) {
822     tr_debug("trps_create_new_idp_realm: unable to allocate new realm.");
823     goto cleanup;
824   }
825   /* fill in the realm */
826   tr_idp_realm_set_id(idp, tr_dup_name(realm_id));
827   if (tr_idp_realm_get_id(idp)==NULL) {
828     tr_debug("trps_create_new_idp_realm: unable to allocate realm name.");
829     idp=NULL;
830     goto cleanup;
831   }
832
833   /* Set the APCs. If the community is a CoI, copy its APCs. If it is an APC, then
834    * that community itself is the APC for the realm. */
835   if (trp_inforec_get_comm_type(rec) == TR_COMM_APC) {
836     /* the community is an APC for this realm */
837     realm_apcs = tr_apc_new(tmp_ctx);
838     if (realm_apcs == NULL) {
839       tr_debug("trps_create_new_idp_realm: unable to allocate new APC list.");
840       idp = NULL;
841       goto cleanup;
842     }
843
844     tr_apc_set_id(realm_apcs, tr_dup_name(comm_id));
845     if (tr_apc_get_id(realm_apcs) == NULL) {
846       tr_debug("trps_create_new_idp_realm: unable to allocate new APC name.");
847       idp = NULL;
848       goto cleanup;
849     }
850   } else {
851     /* the community is not an APC for this realm */
852     realm_apcs = trp_inforec_get_apcs(rec);
853     if (realm_apcs == NULL) {
854       tr_debug("trps_create_new_idp_realm: no APCs for realm %.*s/%.*s, cannot add.",
855                realm_id->len, realm_id->buf,
856                comm_id->len, comm_id->buf);
857       idp = NULL;
858       goto cleanup;
859     }
860
861     /* we have APCs, make our own copy */
862     realm_apcs = tr_apc_dup(tmp_ctx, realm_apcs);
863     if (realm_apcs == NULL) {
864       tr_debug("trps_create_new_idp_realm: unable to duplicate APC list.");
865       idp = NULL;
866       goto cleanup;
867     }
868   }
869
870   /* Whether the community is an APC or CoI, the APCs for the realm are in realm_apcs */
871   tr_idp_realm_set_apcs(idp, realm_apcs); /* takes realm_apcs out of tmp_ctx on success */
872   if (tr_idp_realm_get_apcs(idp) == NULL) {
873     tr_debug("trps_create_new_idp_realm: unable to set APC list for new realm.");
874     idp=NULL;
875     goto cleanup;
876   }
877
878   idp->origin=TR_REALM_DISCOVERED;
879   
880   talloc_steal(mem_ctx, idp);
881   
882 cleanup:
883   talloc_free(tmp_ctx);
884   return idp;
885 }
886
887 static TRP_RC trps_handle_inforec_comm(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
888 {
889   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
890   TR_NAME *comm_id=trp_upd_get_comm(upd);
891   TR_NAME *realm_id=trp_upd_get_realm(upd);
892   TR_NAME *origin_id=NULL;
893   TR_NAME *our_peer_label=NULL;
894   TR_COMM *comm=NULL;
895   TR_RP_REALM *rp_realm=NULL;
896   TR_IDP_REALM *idp_realm=NULL;
897   struct timespec expiry={0,0};
898   TRP_RC rc=TRP_ERROR;
899
900   if ((comm_id==NULL) || (realm_id==NULL))
901     goto cleanup;
902
903   origin_id=trp_inforec_dup_origin(rec);
904   if (origin_id==NULL)
905     goto cleanup;
906     
907   /* see whether we want to add this */
908   our_peer_label=trps_dup_label(trps);
909   if (our_peer_label==NULL) {
910     tr_debug("trps_handle_inforec_comm: unable to allocate peer label.");
911     goto cleanup;
912   }
913
914   if (trps_name_in_provenance(our_peer_label, trp_inforec_get_provenance(rec)))
915     tr_debug("trps_handle_inforec_comm: rejecting community inforec to avoid provenance loop.");
916   else {
917     /* no loop occurring, accept the update */
918     comm=tr_comm_table_find_comm(trps->ctable, comm_id);
919     if (comm==NULL) {
920       tr_debug("trps_handle_inforec_comm: unknown community %.*s in inforec, creating it.",
921                comm_id->len, comm_id->buf);
922       comm=trps_create_new_comm(tmp_ctx, comm_id, rec);
923       if (comm==NULL) {
924         tr_debug("trps_handle_inforec_comm: unable to create new community.");
925         goto cleanup;
926       }
927       if (tr_comm_table_add_comm(trps->ctable, comm) != 0)
928       {
929         tr_debug("trps_handle_inforec_comm: unable to add community to community table.");
930         goto cleanup;
931       }
932     }
933     /* TODO: see if other comm data match the new inforec and update or complain */
934
935     trps_compute_expiry(trps, trp_inforec_get_interval(rec), &expiry);
936     if ((expiry.tv_sec==0)&&(expiry.tv_nsec==0))
937       goto cleanup;
938
939     switch (trp_inforec_get_role(rec)) {
940     case TR_ROLE_RP:
941       rp_realm=tr_rp_realm_lookup(trps->ctable->rp_realms, realm_id);
942       if (rp_realm==NULL) {
943         tr_debug("trps_handle_inforec_comm: unknown RP realm %.*s in inforec, creating it.",
944                  realm_id->len, realm_id->buf);
945         rp_realm= trps_create_new_rp_realm(tmp_ctx, tr_comm_get_id(comm), realm_id, rec);
946         if (rp_realm==NULL) {
947           tr_debug("trps_handle_inforec_comm: unable to create new RP realm.");
948           /* we may leave an unused community in the table, but it will only last until
949            * the next table sweep if it does not get any realms before that happens */
950           goto cleanup;
951         }
952         tr_comm_table_add_rp_realm(trps->ctable, rp_realm);
953       }
954       /* TODO: if realm existed, see if data match the new inforec and update or complain */
955       tr_comm_add_rp_realm(trps->ctable, comm, rp_realm, trp_inforec_get_interval(rec), trp_inforec_get_provenance(rec), &expiry);
956       tr_debug("trps_handle_inforec_comm: added RP realm %.*s to comm %.*s (origin %.*s).",
957                realm_id->len, realm_id->buf,
958                comm_id->len, comm_id->buf,
959                origin_id->len, origin_id->buf);
960       break;
961     case TR_ROLE_IDP:
962       idp_realm=tr_idp_realm_lookup(trps->ctable->idp_realms, realm_id);
963       if (idp_realm==NULL) {
964         tr_debug("trps_handle_inforec_comm: unknown IDP realm %.*s in inforec, creating it.",
965                  realm_id->len, realm_id->buf);
966         idp_realm= trps_create_new_idp_realm(tmp_ctx, tr_comm_get_id(comm), realm_id, rec);
967         if (idp_realm==NULL) {
968           tr_debug("trps_handle_inforec_comm: unable to create new IDP realm.");
969           /* we may leave an unused community in the table, but it will only last until
970            * the next table sweep if it does not get any realms before that happens */
971           goto cleanup;
972         }
973         tr_comm_table_add_idp_realm(trps->ctable, idp_realm);
974       }
975       /* TODO: if realm existed, see if data match the new inforec and update or complain */
976       tr_comm_add_idp_realm(trps->ctable, comm, idp_realm, trp_inforec_get_interval(rec), trp_inforec_get_provenance(rec), &expiry);
977       tr_debug("trps_handle_inforec_comm: added IDP realm %.*s to comm %.*s (origin %.*s).",
978                realm_id->len, realm_id->buf,
979                comm_id->len, comm_id->buf,
980                origin_id->len, origin_id->buf);
981       break;
982     default:
983       tr_debug("trps_handle_inforec_comm: unable to add realm.");
984       goto cleanup;
985     }
986   } 
987
988   rc=TRP_SUCCESS;
989
990 cleanup:
991   if (our_peer_label!=NULL)
992     tr_free_name(our_peer_label);
993   if (origin_id!=NULL)
994     tr_free_name(origin_id);
995   talloc_free(tmp_ctx);
996   return rc;
997 }
998
999 /**
1000  * Apply applicable TRP_INBOUND filters to an inforec. Rejects everything if peer has no filters.
1001  *
1002  * @param trps Active TRPS instance
1003  * @param upd TRP_UPD that contains the inforec to filter
1004  * @param rec Inforec to filter
1005  * @return 1 if accepted by the filter, 0 otherwise
1006  */
1007 static int trps_filter_inbound_inforec(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
1008 {
1009   TRP_PEER *peer=NULL;
1010   TR_NAME *peer_name=NULL;
1011   TR_FILTER_ACTION action=TR_FILTER_ACTION_REJECT;
1012   TR_FILTER_TARGET *target=NULL;
1013   int retval=0;
1014
1015   /* Look up the peer. For inbound messages, the peer is identified by its GSS name */
1016   peer_name=trp_upd_get_peer(upd);
1017   peer=trps_get_peer_by_gssname(trps, peer_name);
1018   if (peer==NULL) {
1019     tr_err("trps_filter_inbound_inforec: received inforec from unknown peer (%.*s), rejecting.",
1020            peer_name->len,
1021            peer_name->buf);
1022     return 0;
1023   }
1024
1025   /* tr_filter_apply() and tr_filter_set_get() handle null filter sets/filters by rejecting */
1026   target= tr_filter_target_trp_inforec(NULL, upd, rec);
1027   if (target==NULL) {
1028     /* TODO: signal that filtering failed. Until then, just filter everything and give an error message. */
1029     tr_crit("trps_filter_inbound_inforec: Unable to allocate filter target, cannot apply filter!");
1030   }
1031   if ((target==NULL)
1032       || (TR_FILTER_NO_MATCH==tr_filter_apply(target,
1033                                               tr_filter_set_get(peer->filters, TR_FILTER_TYPE_TRP_INBOUND),
1034                                               NULL,
1035                                               &action))
1036       || (action!=TR_FILTER_ACTION_ACCEPT)) {
1037     /* either the filter did not match or it matched a reject rule or allocating the target failed */
1038     retval=0;
1039   } else
1040     retval=1;
1041   if (target!=NULL)
1042     tr_filter_target_free(target);
1043
1044   /* filter matched an accept rule */
1045   return retval;
1046 }
1047
1048
1049 static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
1050 {
1051   TRP_INFOREC *rec=NULL;
1052
1053   if (trps_validate_update(trps, upd) != TRP_SUCCESS) {
1054     tr_notice("trps_handle_update: received invalid TRP update.");
1055     return TRP_ERROR;
1056   }
1057
1058   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
1059     /* validate/sanity check the record update */
1060     if (trps_validate_inforec(trps, rec) != TRP_SUCCESS) {
1061       tr_notice("trps_handle_update: invalid inforec in TRP update, discarding entire update.");
1062       return TRP_ERROR;
1063     }
1064   }
1065
1066   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
1067     if (!trps_filter_inbound_inforec(trps, upd, rec)) {
1068       tr_debug("trps_handle_update: inforec rejected by filter.");
1069       continue; /* just go on to the next record */
1070     }
1071
1072     switch (trp_inforec_get_type(rec)) {
1073     case TRP_INFOREC_TYPE_ROUTE:
1074       tr_debug("trps_handle_update: handling route inforec.");
1075       if (TRP_SUCCESS!=trps_handle_inforec_route(trps, upd, rec))
1076         tr_notice("trps_handle_update: error handling route inforec.");
1077       break;
1078     case TRP_INFOREC_TYPE_COMMUNITY:
1079       tr_debug("trps_handle_update: handling community inforec.");
1080       if (TRP_SUCCESS!=trps_handle_inforec_comm(trps, upd, rec))
1081         tr_notice("trps_handle_update: error handling community inforec.");
1082
1083       break;
1084     default:
1085       tr_notice("trps_handle_update: unsupported inforec in TRP update.");
1086       break;
1087     }
1088   }
1089   return TRP_SUCCESS;
1090 }
1091
1092 static TRP_RC trps_validate_request(TRPS_INSTANCE *trps, TRP_REQ *req)
1093 {
1094   if (req==NULL) {
1095     tr_notice("trps_validate_request: null TRP request.");
1096     return TRP_BADARG;
1097   }
1098
1099   if (trp_req_get_comm(req)==NULL) {
1100     tr_notice("trps_validate_request: received TRP request with null community.");
1101     return TRP_ERROR;
1102   }
1103   
1104   if (trp_req_get_realm(req)==NULL) {
1105     tr_notice("trps_validate_request: received TRP request with null realm.");
1106     return TRP_ERROR;
1107   }
1108   
1109   if (trp_req_get_peer(req)==NULL) {
1110     tr_notice("trps_validate_request: received TRP request without origin peer information.");
1111     return TRP_ERROR;
1112   }
1113   
1114   return TRP_SUCCESS;
1115 }
1116
1117 /* choose the best route to comm/realm, optionally excluding routes to a particular peer */
1118 static TRP_ROUTE *trps_find_best_route(TRPS_INSTANCE *trps,
1119                                        TR_NAME *comm,
1120                                        TR_NAME *realm,
1121                                        TR_NAME *exclude_peer_label)
1122 {
1123   TRP_ROUTE **entry=NULL;
1124   TRP_ROUTE *best=NULL;
1125   TRP_PEER *route_peer = NULL;
1126   size_t n_entry=0;
1127   unsigned int kk=0;
1128   unsigned int kk_min=0;
1129   unsigned int min_metric=TRP_METRIC_INFINITY;
1130
1131   entry=trp_rtable_get_realm_entries(trps->rtable, comm, realm, &n_entry);
1132   for (kk=0; kk<n_entry; kk++) {
1133     if (trp_route_get_metric(entry[kk]) < min_metric) {
1134       if (exclude_peer_label != NULL) {
1135         if (!trp_route_is_local(entry[kk])) {
1136           /* route is not local, check the peer label */
1137           route_peer = trp_ptable_find_gss_name(trps->ptable,
1138                                                 trp_route_get_peer(entry[kk]));
1139           if (route_peer == NULL) {
1140             tr_err("trps_find_best_route: unknown peer GSS name (%.*s) for route %d to %.*s/%.*s",
1141                    trp_route_get_peer(entry[kk])->len, trp_route_get_peer(entry[kk])->buf,
1142                    kk,
1143                    realm->len, realm->buf,
1144                    comm->len, comm->buf);
1145             continue; /* unknown peer, skip the route */
1146           }
1147           if (0 == tr_name_cmp(exclude_peer_label, trp_peer_get_label(route_peer))) {
1148             /* we're excluding this peer - skip the route */
1149             continue;
1150           }
1151         }
1152       }
1153       /* if we get here, we're not excluding the route */
1154       kk_min = kk;
1155       min_metric = trp_route_get_metric(entry[kk]);
1156     }
1157   }
1158
1159   if (trp_metric_is_finite(min_metric))
1160     best=entry[kk_min];
1161   
1162   talloc_free(entry);
1163   return best;
1164 }
1165
1166 /* TODO: think this through more carefully. At least ought to add hysteresis
1167  * to avoid flapping between routers or routes. */
1168 TRP_RC trps_update_active_routes(TRPS_INSTANCE *trps)
1169 {
1170   size_t n_comm=0, ii=0;
1171   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
1172   size_t n_realm=0, jj=0;
1173   TR_NAME **realm=NULL;
1174   TRP_ROUTE *best_route=NULL, *cur_route=NULL;
1175   unsigned int best_metric=0, cur_metric=0;
1176
1177   for (ii=0; ii<n_comm; ii++) {
1178     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
1179     for (jj=0; jj<n_realm; jj++) {
1180       best_route=trps_find_best_route(trps, comm[ii], realm[jj], NULL);
1181       if (best_route==NULL)
1182         best_metric=TRP_METRIC_INFINITY;
1183       else
1184         best_metric=trp_route_get_metric(best_route);
1185
1186       cur_route=trps_get_selected_route(trps, comm[ii], realm[jj]);
1187       if (cur_route!=NULL) {
1188         cur_metric=trp_route_get_metric(cur_route);
1189         if ((best_metric < cur_metric) && (trp_metric_is_finite(best_metric))) {
1190           /* The new route has a lower metric than the previous, and is finite. Accept. */
1191           trp_route_set_selected(cur_route, 0);
1192           trp_route_set_selected(best_route, 1);
1193         } else if (!trp_metric_is_finite(cur_metric)) /* rejects infinite or invalid metrics */
1194           trp_route_set_selected(cur_route, 0);
1195       } else if (trp_metric_is_finite(best_metric)) {
1196         trp_route_set_selected(best_route, 1);
1197       }
1198     }
1199     if (realm!=NULL)
1200       talloc_free(realm);
1201     realm=NULL; n_realm=0;
1202   }
1203   if (comm!=NULL)
1204     talloc_free(comm);
1205   comm=NULL; n_comm=0;
1206
1207   return TRP_SUCCESS;
1208 }
1209
1210 /* true if curtime >= expiry */
1211 static int trps_expired(struct timespec *expiry, struct timespec *curtime)
1212 {
1213   return (tr_cmp_timespec(curtime, expiry) >= 0);
1214 }
1215
1216 /* Sweep for expired routes. For each expired route, if its metric is infinite, the route is flushed.
1217  * If its metric is finite, the metric is set to infinite and the route's expiration time is updated. */
1218 TRP_RC trps_sweep_routes(TRPS_INSTANCE *trps)
1219 {
1220   struct timespec sweep_time={0,0};
1221   TRP_ROUTE **entry=NULL;
1222   size_t n_entry=0;
1223   size_t ii=0;
1224
1225   /* use a single time for the entire sweep */
1226   if (0!=clock_gettime(TRP_CLOCK, &sweep_time)) {
1227     tr_err("trps_sweep_routes: could not read realtime clock.");
1228     sweep_time.tv_sec=0;
1229     sweep_time.tv_nsec=0;
1230     return TRP_ERROR;
1231   }
1232
1233   entry= trp_rtable_get_entries(NULL, trps->rtable, &n_entry); /* must talloc_free *entry */
1234
1235   /* loop over the entries */
1236   for (ii=0; ii<n_entry; ii++) {
1237     if (!trp_route_is_local(entry[ii]) && trps_expired(trp_route_get_expiry(entry[ii]), &sweep_time)) {
1238       tr_debug("trps_sweep_routes: route expired.");
1239       if (!trp_metric_is_finite(trp_route_get_metric(entry[ii]))) {
1240         /* flush route */
1241         tr_debug("trps_sweep_routes: metric was infinity, flushing route.");
1242         trp_rtable_remove(trps->rtable, entry[ii]); /* entry[ii] is no longer valid */
1243         entry[ii]=NULL;
1244       } else {
1245         /* set metric to infinity and reset timer */
1246         tr_debug("trps_sweep_routes: setting metric to infinity and resetting expiry.");
1247         trp_route_set_metric(entry[ii], TRP_METRIC_INFINITY);
1248         trp_route_set_expiry(entry[ii], trps_compute_expiry(trps,
1249                                                              trp_route_get_interval(entry[ii]),
1250                                                              trp_route_get_expiry(entry[ii])));
1251       }
1252     }
1253   }
1254
1255   talloc_free(entry);
1256   return TRP_SUCCESS;
1257 }
1258
1259
1260 /* Sweep for expired communities/realms/memberships. */
1261 TRP_RC trps_sweep_ctable(TRPS_INSTANCE *trps)
1262 {
1263   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1264   struct timespec sweep_time={0,0};
1265   struct timespec tmp = {0};
1266   TR_COMM_MEMB *memb=NULL;
1267   TR_COMM_ITER *iter=NULL;
1268   TRP_RC rc=TRP_ERROR;
1269
1270   /* use a single time for the entire sweep */
1271   if (0!=clock_gettime(TRP_CLOCK, &sweep_time)) {
1272     tr_err("trps_sweep_ctable: could not read realtime clock.");
1273     sweep_time.tv_sec=0;
1274     sweep_time.tv_nsec=0;
1275     goto cleanup;
1276   }
1277
1278   /* iterate all memberships */
1279   iter=tr_comm_iter_new(tmp_ctx);
1280   if (iter==NULL) {
1281     tr_err("trps_sweep_ctable: unable to allocate iterator.");
1282     rc=TRP_NOMEM;
1283     goto cleanup;
1284   }
1285   for (memb=tr_comm_memb_iter_all_first(iter, trps->ctable);
1286        memb!=NULL;
1287        memb=tr_comm_memb_iter_all_next(iter)) {
1288     if (tr_comm_memb_get_origin(memb)==NULL)
1289       continue; /* do not expire local entries */
1290
1291     if (tr_comm_memb_is_expired(memb, &sweep_time)) {
1292       if (tr_comm_memb_get_times_expired(memb)>0) {
1293         /* Already expired once; flush. */
1294         tr_debug("trps_sweep_ctable: flushing expired community membership (%.*s in %.*s, origin %.*s, expired %s).",
1295                  tr_comm_memb_get_realm_id(memb)->len, tr_comm_memb_get_realm_id(memb)->buf,
1296                  tr_comm_get_id(tr_comm_memb_get_comm(memb))->len, tr_comm_get_id(tr_comm_memb_get_comm(memb))->buf,
1297                  tr_comm_memb_get_origin(memb)->len, tr_comm_memb_get_origin(memb)->buf,
1298                  timespec_to_str(tr_comm_memb_get_expiry_realtime(memb, &tmp)));
1299         tr_comm_table_remove_memb(trps->ctable, memb);
1300         tr_comm_memb_free(memb);
1301       } else {
1302         /* This is the first expiration. Note this and reset the expiry time. */
1303         tr_comm_memb_expire(memb);
1304         trps_compute_expiry(trps, tr_comm_memb_get_interval(memb), tr_comm_memb_get_expiry(memb));
1305         tr_debug("trps_sweep_ctable: community membership expired at %s, resetting expiry to %s (%.*s in %.*s, origin %.*s).",
1306                  timespec_to_str(tr_clock_convert(TRP_CLOCK, &sweep_time, CLOCK_REALTIME, &tmp)),
1307                  timespec_to_str(tr_comm_memb_get_expiry_realtime(memb, &tmp)),
1308                  tr_comm_memb_get_realm_id(memb)->len, tr_comm_memb_get_realm_id(memb)->buf,
1309                  tr_comm_get_id(tr_comm_memb_get_comm(memb))->len, tr_comm_get_id(tr_comm_memb_get_comm(memb))->buf,
1310                  tr_comm_memb_get_origin(memb)->len, tr_comm_memb_get_origin(memb)->buf);
1311       }
1312     }
1313   }
1314
1315   /* get rid of any unreferenced realms, etc */
1316   tr_comm_table_sweep(trps->ctable);
1317
1318 cleanup:
1319   talloc_free(tmp_ctx);
1320   return rc;
1321 }
1322
1323 /* add metrics */
1324 static unsigned int trps_metric_add(unsigned int m1, unsigned int m2)
1325 {
1326   if (trp_metric_is_invalid(m1) || trp_metric_is_invalid(m2))
1327     return TRP_METRIC_INVALID;
1328
1329   if (trp_metric_is_infinite(m1) || trp_metric_is_infinite(m2))
1330     return TRP_METRIC_INFINITY;
1331
1332   if (trp_metric_is_finite(m1+m2))
1333     return m1+m2;
1334   else
1335     return TRP_METRIC_INFINITY;
1336 }
1337
1338 /* convert an rentry into a new trp update info record */
1339 static TRP_INFOREC *trps_route_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
1340 {
1341   TRP_INFOREC *rec=trp_inforec_new(mem_ctx, TRP_INFOREC_TYPE_ROUTE);
1342   unsigned int linkcost=0;
1343
1344   if (rec!=NULL) {
1345     if (trp_route_is_local(route))
1346       linkcost=0;
1347     else {
1348       linkcost=trp_peer_get_linkcost(trps_get_peer_by_gssname(trps,
1349                                                               trp_route_get_peer(route)));
1350     }
1351
1352     /* Note that we leave the next hop empty since the recipient fills that in.
1353      * This is where we add the link cost (currently always 1) to the next peer. */
1354     if ((trp_inforec_set_trust_router(rec, trp_route_dup_trust_router(route)) != TRP_SUCCESS)
1355        ||(trp_inforec_set_metric(rec,
1356                                  trps_metric_add(trp_route_get_metric(route),
1357                                                  linkcost)) != TRP_SUCCESS)
1358        ||(trp_inforec_set_interval(rec, trps_get_update_interval(trps)) != TRP_SUCCESS)) {
1359       tr_err("trps_route_to_inforec: error creating route update.");
1360       talloc_free(rec);
1361       rec=NULL;
1362     }
1363   }
1364   return rec;
1365 }
1366
1367 static TRP_UPD *trps_route_to_upd(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
1368 {
1369   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1370   TRP_UPD *upd=trp_upd_new(tmp_ctx);
1371   TRP_INFOREC *rec=NULL;
1372
1373   if (upd==NULL) {
1374     tr_err("trps_route_to_upd: could not create update message.");
1375     goto cleanup;
1376   }
1377   trp_upd_set_realm(upd, trp_route_dup_realm(route));
1378   if (trp_upd_get_realm(upd)==NULL) {
1379     tr_err("trps_route_to_upd: could not copy realm.");
1380     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
1381     goto cleanup;
1382   }
1383   trp_upd_set_comm(upd, trp_route_dup_comm(route));
1384   if (trp_upd_get_comm(upd)==NULL) {
1385     tr_err("trps_route_to_upd: could not copy comm.");
1386     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
1387     goto cleanup;
1388   }
1389   rec=trps_route_to_inforec(tmp_ctx, trps, route);
1390   if (rec==NULL) {
1391     tr_err("trps_route_to_upd: could not create route info record for realm %.*s in comm %.*s.",
1392            trp_route_get_realm(route)->len, trp_route_get_realm(route)->buf,
1393            trp_route_get_comm(route)->len, trp_route_get_comm(route)->buf);
1394     upd=NULL; /* it's till in tmp_ctx, so it will be freed */
1395     goto cleanup;
1396   }
1397   trp_upd_add_inforec(upd, rec);
1398
1399   /* sucess */
1400   talloc_steal(mem_ctx, upd);
1401
1402 cleanup:
1403   talloc_free(tmp_ctx);
1404   return upd;
1405 }
1406
1407 /* select the correct route to comm/realm to be announced to peer */
1408 static TRP_ROUTE *trps_select_realm_update(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer_label)
1409 {
1410   TRP_ROUTE *route = NULL;
1411   TRP_PEER *route_peer = NULL;
1412   TR_NAME *route_peer_label = NULL;
1413
1414   /* Take the currently selected route unless it is through the peer we're sending the update to.
1415    * I.e., enforce the split horizon rule. Start by looking up the currently selected route. */
1416   route=trp_rtable_get_selected_entry(trps->rtable, comm, realm);
1417   if (route==NULL) {
1418     /* No selected route, this should only happen if the only route has been retracted,
1419      * in which case we do not want to advertise it. */
1420     return NULL;
1421   }
1422
1423   /* Check whether it's local. */
1424   if (trp_route_is_local(route)) {
1425     /* It is always ok to announce a local route */
1426     tr_debug("trps_select_realm_update: selected route for %.*s/%.*s is local",
1427              realm->len, realm->buf,
1428              comm->len, comm->buf);
1429   } else {
1430     /* It's not local. Get the route's peer and check whether it's the same place we
1431      * got the selected route from. Peer should always correspond to an entry in our
1432      * peer table. */
1433     tr_debug("trps_select_realm_update: selected route for %.*s/%.*s is not local",
1434              realm->len, realm->buf,
1435              comm->len, comm->buf);
1436     route_peer = trp_ptable_find_gss_name(trps->ptable, trp_route_get_peer(route));
1437     if (route_peer == NULL) {
1438       tr_err("trps_select_realm_update: unknown peer GSS name (%.*s) for selected route for %.*s/%.*s",
1439              trp_route_get_peer(route)->len, trp_route_get_peer(route)->buf,
1440              realm->len, realm->buf,
1441              comm->len, comm->buf);
1442       return NULL;
1443     }
1444     route_peer_label = trp_peer_get_label(route_peer);
1445     if (route_peer_label == NULL) {
1446       tr_err("trps_select_realm_update: error retrieving peer label for selected route for %.*s/%.*s",
1447              realm->len, realm->buf,
1448              comm->len, comm->buf);
1449       return NULL;
1450     }
1451
1452     /* see if these match */
1453     tr_debug("trps_select_realm_update: %.*s vs %.*s",
1454              peer_label->len, peer_label->buf,
1455              route_peer_label->len, route_peer_label->buf);
1456
1457     if (0==tr_name_cmp(peer_label, route_peer_label)) {
1458       /* the selected entry goes through the peer we're reporting to, choose an alternate */
1459       tr_debug("trps_select_realm_update: matched, finding alternate route");
1460       route=trps_find_best_route(trps, comm, realm, peer_label);
1461       if ((route==NULL) || (!trp_metric_is_finite(trp_route_get_metric(route)))) {
1462         tr_debug("trps_select_realm_update: no route to %.*s/%.*s suitable to advertise to %.*s",
1463                  realm->len, realm->buf,
1464                  comm->len, comm->buf,
1465                  peer_label->len, peer_label->buf);
1466         return NULL; /* don't advertise a nonexistent or retracted route */
1467       }
1468     }
1469   }
1470   return route;
1471 }
1472
1473 /* Add TRP_UPD msgs to the updates GPtrArray. Caller needs to arrange for these to be freed. */
1474 static TRP_RC trps_select_route_updates_for_peer(TALLOC_CTX *mem_ctx,
1475                                                  GPtrArray *updates,
1476                                                  TRPS_INSTANCE *trps,
1477                                                  TR_NAME *peer_label,
1478                                                  int triggered)
1479 {
1480   size_t n_comm=0;
1481   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
1482   TR_NAME **realm=NULL;
1483   size_t n_realm=0;
1484   size_t ii=0, jj=0;
1485   TRP_ROUTE *best=NULL;
1486   TRP_UPD *upd=NULL;
1487
1488   if (updates==NULL)
1489     return TRP_BADARG;
1490
1491   for (ii=0; ii<n_comm; ii++) {
1492     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
1493     for (jj=0; jj<n_realm; jj++) {
1494       best=trps_select_realm_update(trps, comm[ii], realm[jj], peer_label);
1495       /* If we found a route, add it to the list. If triggered!=0, then only
1496        * add triggered routes. */
1497       if ((best!=NULL) && ((!triggered) || trp_route_is_triggered(best))) {
1498         upd=trps_route_to_upd(mem_ctx, trps, best);
1499         if (upd==NULL) {
1500           tr_err("trps_select_route_updates_for_peer: unable to create update message.");
1501           continue;
1502         }
1503         g_ptr_array_add(updates, upd);
1504       }
1505     }
1506     
1507     if (realm!=NULL)
1508       talloc_free(realm);
1509     realm=NULL;
1510     n_realm=0;
1511   }
1512
1513   if (comm!=NULL)
1514     talloc_free(comm);
1515   
1516   return TRP_SUCCESS;
1517 }
1518
1519 static TRP_INFOREC *trps_memb_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_COMM_MEMB *memb)
1520 {
1521   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1522   TRP_INFOREC *rec=NULL;
1523   TR_COMM *comm=NULL;
1524
1525   if (memb==NULL)
1526     goto cleanup;
1527
1528   comm=tr_comm_memb_get_comm(memb);
1529   rec=trp_inforec_new(tmp_ctx, TRP_INFOREC_TYPE_COMMUNITY);
1530   if (rec==NULL)
1531     goto cleanup;
1532   
1533   if (TRP_SUCCESS!=trp_inforec_set_comm_type(rec, tr_comm_get_type(comm))) {
1534     rec=NULL;
1535     goto cleanup;
1536   }
1537   
1538   if (TRP_SUCCESS!=trp_inforec_set_role(rec, tr_comm_memb_get_role(memb))) {
1539     rec=NULL;
1540     goto cleanup;
1541   }
1542
1543   if ((NULL!=tr_comm_get_apcs(comm)) &&
1544       ( (TRP_SUCCESS!=trp_inforec_set_apcs(rec,
1545                                            tr_apc_dup(rec, tr_comm_get_apcs(comm)))) ||
1546         (NULL==trp_inforec_get_apcs(rec)))) {
1547     rec=NULL;
1548     goto cleanup;
1549   }
1550
1551   if ((NULL!=tr_comm_get_owner_realm(comm)) &&
1552       ( (TRP_SUCCESS!=trp_inforec_set_owner_realm(rec, tr_dup_name(tr_comm_get_owner_realm(comm)))) ||
1553         (NULL==trp_inforec_get_owner_realm(rec)))) {
1554     rec=NULL;
1555     goto cleanup;
1556   }
1557
1558   if ((NULL!=tr_comm_get_owner_contact(comm)) &&
1559       ( (TRP_SUCCESS!=trp_inforec_set_owner_contact(rec, tr_dup_name(tr_comm_get_owner_contact(comm)))) ||
1560         (NULL==trp_inforec_get_owner_contact(rec)))) {
1561     rec=NULL;
1562     goto cleanup;
1563   }
1564
1565   if ((NULL!=tr_comm_memb_get_provenance(memb)) &&
1566       (TRP_SUCCESS!=trp_inforec_set_provenance(rec, tr_comm_memb_get_provenance(memb)))) {
1567     rec=NULL;
1568     goto cleanup;
1569   }
1570
1571   if (TRP_SUCCESS!=trp_inforec_set_interval(rec, trps_get_update_interval(trps))) {
1572     rec=NULL;
1573     goto cleanup;
1574   }
1575
1576   /* success! */
1577   talloc_steal(mem_ctx, rec);
1578
1579 cleanup:
1580   talloc_free(tmp_ctx);
1581   return rec;
1582 }
1583
1584 /* construct an update with all the inforecs for comm/realm/role to be sent to peer */
1585 static TRP_UPD *trps_comm_update(TALLOC_CTX *mem_ctx,
1586                                  TRPS_INSTANCE *trps,
1587                                  TR_NAME *peer_label,
1588                                  TR_COMM *comm,
1589                                  TR_REALM *realm)
1590 {
1591   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1592   TRP_UPD *upd=trp_upd_new(tmp_ctx);
1593   TRP_INFOREC *rec=NULL;
1594   TR_COMM_ITER *iter=NULL;
1595   TR_COMM_MEMB *memb=NULL;
1596
1597   if (upd==NULL)
1598     goto cleanup;
1599   
1600   trp_upd_set_comm(upd, tr_comm_dup_id(comm));
1601   trp_upd_set_realm(upd, tr_realm_dup_id(realm));
1602   /* leave peer empty */
1603
1604   iter=tr_comm_iter_new(tmp_ctx);
1605   if (iter==NULL) {
1606     tr_err("trps_comm_update: unable to allocate iterator.");
1607     upd=NULL;
1608     goto cleanup;
1609   }
1610   
1611   /* now add inforecs */
1612   switch (realm->role) {
1613   case TR_ROLE_IDP:
1614     memb=tr_comm_table_find_idp_memb(trps->ctable,
1615                                      tr_realm_get_id(realm),
1616                                      tr_comm_get_id(comm));
1617     break;
1618   case TR_ROLE_RP:
1619     memb=tr_comm_table_find_rp_memb(trps->ctable,
1620                                     tr_realm_get_id(realm),
1621                                     tr_comm_get_id(comm));
1622     break;
1623   default:
1624     break;
1625   }
1626   if (memb!=NULL) {
1627     for (memb=tr_comm_memb_iter_first(iter, memb);
1628          memb!=NULL;
1629          memb=tr_comm_memb_iter_next(iter)) {
1630       rec=trps_memb_to_inforec(tmp_ctx, trps, memb);
1631       if (rec==NULL) {
1632         tr_err("trps_comm_update: unable to allocate inforec.");
1633         upd=NULL;
1634         goto cleanup;
1635       }
1636       trp_upd_add_inforec(upd, rec);
1637     }
1638   }
1639
1640   if (trp_upd_get_inforec(upd)==NULL)
1641     upd=NULL; /* no inforecs, no reason to send the update */
1642   else
1643     talloc_steal(mem_ctx, upd); /* success! */
1644
1645 cleanup:
1646   talloc_free(tmp_ctx);
1647   return upd;
1648 }
1649
1650 /* Find all community updates to send to a peer and add these as TR_UPD records
1651  * to the updates GPtrArray. */
1652 static TRP_RC trps_select_comm_updates_for_peer(TALLOC_CTX *mem_ctx,
1653                                                 GPtrArray *updates,
1654                                                 TRPS_INSTANCE *trps,
1655                                                 TR_NAME *peer_label,
1656                                                 int triggered)
1657 {
1658   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1659   TR_COMM_ITER *comm_iter=NULL;
1660   TR_COMM *comm=NULL;
1661   TR_COMM_ITER *realm_iter=NULL;
1662   TR_REALM *realm=NULL;
1663   TRP_UPD *upd=NULL;
1664   TRP_RC rc=TRP_ERROR;
1665
1666   /* currently do not send any communities on triggered updates */
1667   if (triggered) {
1668     rc=TRP_SUCCESS;
1669     goto cleanup;
1670   }
1671
1672   comm_iter=tr_comm_iter_new(tmp_ctx);
1673   realm_iter=tr_comm_iter_new(tmp_ctx);
1674   if ((comm_iter==NULL) || (realm_iter==NULL)) {
1675     tr_err("trps_select_comm_updates_for_peer: unable to allocate iterator.");
1676     rc=TRP_NOMEM;
1677     goto cleanup;
1678   }
1679
1680   /* do every community */
1681   for (comm=tr_comm_table_iter_first(comm_iter, trps->ctable);
1682        comm!=NULL;
1683        comm=tr_comm_table_iter_next(comm_iter)) {
1684     /* do every realm in this community */
1685     tr_debug("trps_select_comm_updates_for_peer: looking through community %.*s",
1686              tr_comm_get_id(comm)->len,
1687              tr_comm_get_id(comm)->buf);
1688     for (realm=tr_realm_iter_first(realm_iter, trps->ctable, tr_comm_get_id(comm));
1689          realm!=NULL;
1690          realm=tr_realm_iter_next(realm_iter)) {
1691       /* get the update for this comm/realm */
1692       tr_debug("trps_select_comm_updates_for_peer: adding realm %.*s",
1693                tr_realm_get_id(realm)->len,
1694                tr_realm_get_id(realm)->buf);
1695       upd=trps_comm_update(mem_ctx, trps, peer_label, comm, realm);
1696       if (upd!=NULL)
1697         g_ptr_array_add(updates, upd);
1698     }
1699   }
1700
1701 cleanup:
1702   talloc_free(tmp_ctx);
1703   return rc;
1704 }
1705
1706 /**
1707  * Filter the inforecs in a single update
1708  *
1709  * @param filt The filter to apply
1710  * @param upd The update to filter
1711  */
1712 static void trps_filter_one_outbound_update(TR_FILTER *filt, TRP_UPD *upd)
1713 {
1714   TRP_INFOREC *this=NULL, *next=NULL;
1715   TR_FILTER_ACTION action=TR_FILTER_ACTION_REJECT;
1716   TR_FILTER_TARGET *target=NULL;
1717
1718   for(this=trp_upd_get_inforec(upd); this!=NULL; this=next) {
1719     next=this->next;
1720     target= tr_filter_target_trp_inforec(NULL, upd, this);
1721     if (target==NULL) {
1722       /* TODO: signal that filtering failed. Until then, just filter everything and give an error message. */
1723       tr_crit("trps_filter_one_outbound_update: Unable to allocate filter target, cannot apply filter!");
1724     }
1725     if ((target==NULL)
1726         || (TR_FILTER_NO_MATCH==tr_filter_apply(target, filt, NULL, &action))
1727         || (action!=TR_FILTER_ACTION_ACCEPT)) {
1728       /* Either no filter matched or one matched and rejected this record.
1729        * Also filter out record if we were unable to allocate a target. */
1730       trp_upd_remove_inforec(upd, this); /* "this" is now invalid */
1731     }
1732     if (target!=NULL)
1733       tr_filter_target_free(target);
1734   }
1735 }
1736
1737 /**
1738  * May shuffle the update list.
1739  *
1740  * @param filters The filter set for the relevant TRP peer
1741  * @param updates GPtrArray of updates to filter
1742  */
1743 static void trps_filter_outbound_updates(TR_FILTER_SET *filters, GPtrArray *updates)
1744 {
1745   TRP_UPD *upd=NULL;
1746   guint ii=0;
1747
1748   /* Walk backward through the array so we can remove elements. Careful about loop
1749    * termination - remember that ii is unsigned. */
1750   for (ii=updates->len; ii>0; ii--) {
1751     upd=g_ptr_array_index(updates, ii-1);
1752     trps_filter_one_outbound_update(tr_filter_set_get(filters, TR_FILTER_TYPE_TRP_OUTBOUND), upd);
1753     /* see if we removed all the records from this update */
1754     if (trp_upd_num_inforecs(upd)==0)
1755       g_ptr_array_remove_index_fast(updates, ii-1); /* does not preserve order at index ii or higher */
1756   }
1757 }
1758
1759 /* helper for trps_update_one_peer. Frees the TRP_UPD pointed to by a GPtrArray element */
1760 static void trps_trp_upd_destroy(gpointer data)
1761 {
1762   trp_upd_free((TRP_UPD *)data);
1763 }
1764
1765 /* all routes/communities to a single peer, unless comm/realm are specified (both or neither must be NULL) */
1766 static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
1767                                    TRP_PEER *peer,
1768                                    TRP_UPDATE_TYPE update_type,
1769                                    TR_NAME *realm,
1770                                    TR_NAME *comm)
1771 {
1772   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1773   TR_MSG msg; /* not a pointer! */
1774   TRP_UPD *upd=NULL;
1775   TRP_ROUTE *route=NULL;
1776   size_t ii=0;
1777   char *encoded=NULL;
1778   TRP_RC rc=TRP_ERROR;
1779   TR_NAME *peer_label=trp_peer_get_label(peer);
1780   GPtrArray *updates=g_ptr_array_new_with_free_func(trps_trp_upd_destroy);
1781
1782   if (updates==NULL) {
1783     tr_err("trps_update_one_peer: unable to allocate updates array.");
1784     rc=TRP_NOMEM;
1785     goto cleanup;
1786   }
1787
1788   switch (update_type) {
1789   case TRP_UPDATE_TRIGGERED:
1790     tr_debug("trps_update_one_peer: preparing triggered update for %.*s",
1791              peer_label->len, peer_label->buf);
1792     break;
1793   case TRP_UPDATE_SCHEDULED:
1794     tr_debug("trps_update_one_peer: preparing scheduled update for %.*s",
1795              peer_label->len, peer_label->buf);
1796     break;
1797   case TRP_UPDATE_REQUESTED:
1798     tr_debug("trps_update_one_peer: preparing requested update for %.*s",
1799              peer_label->len, peer_label->buf);
1800     break;
1801   default:
1802     tr_err("trps_update_one_peer: invalid update type requested.");
1803     rc=TRP_BADARG;
1804     goto cleanup;
1805   }
1806
1807   /* First, gather route updates. */
1808   tr_debug("trps_update_one_peer: selecting route updates for %.*s.", peer_label->len, peer_label->buf);
1809   if ((comm==NULL) && (realm==NULL)) {
1810     /* do all realms */
1811     rc=trps_select_route_updates_for_peer(tmp_ctx,
1812                                           updates,
1813                                           trps,
1814                                           peer_label,
1815                                           update_type==TRP_UPDATE_TRIGGERED);
1816   } else if ((comm!=NULL) && (realm!=NULL)) {
1817     /* a single community/realm was requested */
1818     route=trps_select_realm_update(trps, comm, realm, peer_label);
1819     if (route==NULL) {
1820       /* we have no actual update to send back, MUST send a retraction */
1821       tr_debug("trps_update_one_peer: community/realm without route requested, sending mandatory retraction.");
1822       route=trp_route_new(tmp_ctx);
1823       trp_route_set_comm(route, tr_dup_name(comm));
1824       trp_route_set_realm(route, tr_dup_name(realm));
1825       trp_route_set_peer(route, tr_new_name(""));
1826       trp_route_set_metric(route, TRP_METRIC_INFINITY);
1827       trp_route_set_trust_router(route, tr_new_name(""));
1828       trp_route_set_next_hop(route, tr_new_name(""));
1829     }
1830     upd=trps_route_to_upd(tmp_ctx, trps, route);
1831     if (upd==NULL) {
1832       tr_err("trps_update_one_peer: unable to allocate route update.");
1833       rc=TRP_NOMEM;
1834       goto cleanup;
1835     }
1836     g_ptr_array_add(updates, upd);
1837   } else {
1838     tr_err("trps_update_one_peer: error: only comm or realm was specified. Need both or neither.");
1839     rc=TRP_ERROR;
1840     goto cleanup;
1841   }
1842
1843   /* Second, gather community updates */
1844   tr_debug("trps_update_one_peer: selecting community updates for %.*s.", peer_label->len, peer_label->buf);
1845   rc=trps_select_comm_updates_for_peer(tmp_ctx, updates, trps, peer_label, update_type==TRP_UPDATE_TRIGGERED);
1846
1847   /* see if we have anything to send */
1848   if (updates->len<=0)
1849     tr_debug("trps_update_one_peer: no updates for %.*s", peer_label->len, peer_label->buf);
1850   else {
1851     /* Apply outbound TRP filters for this peer */
1852     trps_filter_outbound_updates(peer->filters, updates);
1853
1854     if (updates->len<=0)
1855       tr_debug("trps_update_one_peer: no updates for %.*s after filtering.", peer_label->len, peer_label->buf);
1856     else {
1857       tr_debug("trps_update_one_peer: sending %d update messages.", updates->len);
1858       for (ii=0; ii<updates->len; ii++) {
1859         upd = (TRP_UPD *) g_ptr_array_index(updates, ii);
1860         /* now encode the update message */
1861         tr_msg_set_trp_upd(&msg, upd);
1862         encoded = tr_msg_encode(NULL, &msg);
1863         if (encoded == NULL) {
1864           tr_err("trps_update_one_peer: error encoding update.");
1865           rc = TRP_ERROR;
1866           goto cleanup;
1867         }
1868
1869         tr_debug("trps_update_one_peer: adding message to queue.");
1870         if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
1871           tr_err("trps_update_one_peer: error queueing update.");
1872         else
1873           tr_debug("trps_update_one_peer: update queued successfully.");
1874
1875         tr_msg_free_encoded(encoded);
1876         encoded = NULL;
1877       }
1878     }
1879   }
1880
1881   rc=TRP_SUCCESS;
1882
1883 cleanup:
1884   if (updates!=NULL)
1885     g_ptr_array_free(updates, TRUE); /* frees any TRP_UPD records */
1886   talloc_free(tmp_ctx);
1887   return rc;
1888 }
1889
1890 /* all routes/communities to all peers */
1891 TRP_RC trps_update(TRPS_INSTANCE *trps, TRP_UPDATE_TYPE update_type)
1892 {
1893   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1894   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
1895   TRP_PEER *peer=NULL;
1896   TRP_RC rc=TRP_SUCCESS;
1897
1898   if (trps->ptable==NULL)
1899     return TRP_SUCCESS; /* no peers, nothing to do */
1900
1901   if (iter==NULL) {
1902     tr_err("trps_update: failed to allocate peer table iterator.");
1903     talloc_free(tmp_ctx);
1904     return TRP_NOMEM;
1905   }
1906
1907   for (peer=trp_ptable_iter_first(iter, trps->ptable);
1908        (peer!=NULL) && (rc==TRP_SUCCESS);
1909        peer=trp_ptable_iter_next(iter))
1910   {
1911     if (!trps_peer_connected(trps, peer)) {
1912       TR_NAME *peer_label=trp_peer_get_label(peer);
1913       tr_debug("trps_update: no TRP connection to %.*s, skipping.",
1914                peer_label->len, peer_label->buf);
1915       continue;
1916     }
1917     rc=trps_update_one_peer(trps, peer, update_type, NULL, NULL);
1918   }
1919
1920   tr_debug("trps_update: rc=%u after attempting update.", rc);
1921   trp_ptable_iter_free(iter);
1922   trp_rtable_clear_triggered(trps->rtable); /* don't re-send triggered updates */
1923   talloc_free(tmp_ctx);
1924   return rc;
1925 }        
1926
1927 TRP_RC trps_add_route(TRPS_INSTANCE *trps, TRP_ROUTE *route)
1928 {
1929   trp_rtable_add(trps->rtable, route); /* should return status */
1930   return TRP_SUCCESS; 
1931 }
1932
1933 /* steals the peer object */
1934 TRP_RC trps_add_peer(TRPS_INSTANCE *trps, TRP_PEER *peer)
1935 {
1936   if (trps->ptable==NULL) {
1937     trps->ptable=trp_ptable_new(trps);
1938     if (trps->ptable==NULL)
1939       return TRP_NOMEM;
1940   }
1941   return trp_ptable_add(trps->ptable, peer);
1942 }
1943
1944 TRP_PEER *trps_get_peer_by_gssname(TRPS_INSTANCE *trps, TR_NAME *gssname)
1945 {
1946   if (trps->ptable==NULL)
1947     return NULL;
1948
1949   return trp_ptable_find_gss_name(trps->ptable, gssname);
1950 }
1951
1952 TRP_PEER *trps_get_peer_by_servicename(TRPS_INSTANCE *trps, TR_NAME *servicename)
1953 {
1954   if (trps->ptable==NULL)
1955     return NULL;
1956
1957   return trp_ptable_find_servicename(trps->ptable, servicename);
1958 }
1959
1960 int trps_peer_connected(TRPS_INSTANCE *trps, TRP_PEER *peer)
1961 {
1962   TRPC_INSTANCE *trpc=trps_find_trpc(trps, peer);
1963   if (trpc==NULL)
1964     return 0;
1965
1966   if (trpc_get_status(trpc)==TRP_CONNECTION_UP)
1967     return 1;
1968   else
1969     return 0;
1970 }
1971
1972
1973 static TRP_RC trps_handle_request(TRPS_INSTANCE *trps, TRP_REQ *req)
1974 {
1975   TR_NAME *comm=NULL;
1976   TR_NAME *realm=NULL;
1977
1978   tr_debug("trps_handle_request: handling TRP request.");
1979
1980   if (trps_validate_request(trps, req) != TRP_SUCCESS) {
1981     tr_notice("trps_handle_request: received invalid TRP request.");
1982     return TRP_ERROR;
1983   }
1984
1985   if (!trp_req_is_wildcard(req)) {
1986     comm=trp_req_get_comm(req);
1987     realm=trp_req_get_realm(req);
1988     tr_debug("trps_handle_request: route for %.*s/%.*s requested.",
1989              comm->len, comm->buf, realm->len, realm->buf);
1990   } else {
1991     tr_debug("trps_handle_request: all routes requested.");
1992     /* leave comm/realm NULL */
1993   }
1994   return trps_update_one_peer(trps,
1995                               trps_get_peer_by_gssname(trps, trp_req_get_peer(req)),
1996                               TRP_UPDATE_REQUESTED,
1997                               realm,
1998                               comm);
1999 }
2000
2001
2002 TRP_RC trps_handle_tr_msg(TRPS_INSTANCE *trps, TR_MSG *tr_msg)
2003 {
2004   TRP_RC rc=TRP_ERROR;
2005
2006   switch (tr_msg_get_msg_type(tr_msg)) {
2007   case TRP_UPDATE:
2008     rc=trps_handle_update(trps, tr_msg_get_trp_upd(tr_msg));
2009     if (rc==TRP_SUCCESS) {
2010       rc=trps_update_active_routes(trps);
2011       trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
2012     }
2013     return rc;
2014
2015   case TRP_REQUEST:
2016     rc=trps_handle_request(trps, tr_msg_get_trp_req(tr_msg));
2017     return rc;
2018
2019   default:
2020     /* unknown error or one we don't care about (e.g., TID messages) */
2021     return TRP_ERROR;
2022   }
2023 }
2024
2025 /* send wildcard route request to a peer */
2026 TRP_RC trps_wildcard_route_req(TRPS_INSTANCE *trps, TR_NAME *peer_servicename)
2027 {
2028   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
2029   TRP_PEER *peer=trps_get_peer_by_servicename(trps, peer_servicename);
2030   TR_MSG msg; /* not a pointer */
2031   TRP_REQ *req=trp_req_new(tmp_ctx);
2032   char *encoded=NULL;
2033   TRP_RC rc=TRP_ERROR;
2034
2035   if (peer==NULL) {
2036     tr_err("trps_wildcard_route_req: unknown peer (%.*s).", peer_servicename->len, peer_servicename->buf);
2037     rc=TRP_BADARG;
2038     goto cleanup;
2039   }
2040   if ((req==NULL) || (trp_req_make_wildcard(req)!=TRP_SUCCESS)) {
2041     tr_err("trps_wildcard_route_req: unable to create wildcard TRP request.");
2042     rc=TRP_NOMEM;
2043     goto cleanup;
2044   }
2045
2046   tr_msg_set_trp_req(&msg, req);
2047   encoded= tr_msg_encode(NULL, &msg);
2048   if (encoded==NULL) {
2049     tr_err("trps_wildcard_route_req: error encoding wildcard TRP request.");
2050     rc=TRP_ERROR;
2051     goto cleanup;
2052   }
2053
2054   tr_debug("trps_wildcard_route_req: adding message to queue.");
2055   if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS) {
2056     tr_err("trps_wildcard_route_req: error queueing request.");
2057     rc=TRP_ERROR;
2058   } else {
2059     tr_debug("trps_wildcard_route_req: request queued successfully.");
2060     rc=TRP_SUCCESS;
2061   }
2062
2063 cleanup:
2064   if (encoded!=NULL)
2065     tr_msg_free_encoded(encoded);
2066   if (req!=NULL)
2067     trp_req_free(req);
2068
2069   talloc_free(tmp_ctx);
2070   return rc;
2071 }