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