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