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