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