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