Raise priority of error messages when cannot open a socket
[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 <tr_name_internal.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   if (trps->ptable!=NULL)
172     trp_ptable_free(trps->ptable);
173   trps->ptable=ptable;
174 }
175
176 void trps_set_peer_status_callback(TRPS_INSTANCE *trps, void (*cb)(TRP_PEER *, void *), void *cookie)
177 {
178   TRP_PTABLE_ITER *iter=NULL;
179   TRP_PEER *peer=NULL;
180   if (trps->ptable==NULL)
181     return;
182
183   iter=trp_ptable_iter_new(NULL);
184   for (peer=trp_ptable_iter_first(iter, trps->ptable); peer!=NULL; peer=trp_ptable_iter_next(iter))
185     trp_peer_set_conn_status_cb(peer, cb, cookie);
186   trp_ptable_iter_free(iter);
187 }
188
189 /* Get the label peers will know us by - needs to match trp_peer_get_label() output.
190  * There is no get, only dup, because we don't store the label except when requested. */
191 TR_NAME *trps_dup_label(TRPS_INSTANCE *trps)
192 {
193   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
194   TR_NAME *label=NULL;
195   char *s=talloc_asprintf(tmp_ctx, "%s:%u", trps->hostname, trps->port);
196   if (s==NULL)
197     goto cleanup;
198   label=tr_new_name(s);
199
200 cleanup:
201   talloc_free(tmp_ctx);
202   return label;
203 }
204
205 TRPC_INSTANCE *trps_find_trpc(TRPS_INSTANCE *trps, TRP_PEER *peer)
206 {
207   TRPC_INSTANCE *cur=NULL;
208   TR_NAME *name=NULL;
209   TR_NAME *peer_servicename=trp_peer_get_servicename(peer);
210
211   for (cur=trps->trpc; cur!=NULL; cur=trpc_get_next(cur)) {
212     name=trpc_get_gssname(cur);
213     if ((name!=NULL) && (0==tr_name_cmp(peer_servicename, name))) {
214       break;
215     }
216   }
217   return cur;
218 }
219
220 void trps_add_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *new)
221 {
222   if (trps->conn==NULL)
223     trps->conn=new;
224   else
225     trp_connection_append(trps->conn, new);
226
227   talloc_steal(trps, new);
228 }
229
230 /* ok to call more than once; guarantees connection no longer in the list.
231  * Caller is responsible for freeing the removed element afterwards.  */
232 void trps_remove_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *remove)
233 {
234   trps->conn=trp_connection_remove(trps->conn, remove);
235 }
236
237 void trps_add_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *trpc)
238 {
239   if (trps->trpc==NULL)
240     trps->trpc=trpc;
241   else
242     trpc_append(trps->trpc, trpc);
243
244   talloc_steal(trps, trpc);
245 }
246
247 /* ok to call more than once; guarantees trpc no longer in the list.
248  * Caller is responsible for freeing the removed element afterwards.  */
249 void trps_remove_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *remove)
250 {
251   trps->trpc=trpc_remove(trps->trpc, remove);
252 }
253
254 TRP_RC trps_send_msg(TRPS_INSTANCE *trps, TRP_PEER *peer, const char *msg)
255 {
256   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
257   TR_MQ_MSG *mq_msg=NULL;
258   char *msg_dup=NULL;
259   TRP_RC rc=TRP_ERROR;
260   TRPC_INSTANCE *trpc=NULL;
261
262   /* get the connection for this peer */
263   trpc=trps_find_trpc(trps, peer);
264   /* instead, let's let that happen and then clear the queue when an attempt to
265    * connect fails */
266   if (trpc==NULL) {
267     tr_warning("trps_send_msg: skipping message queued for missing TRP client entry.");
268   } else {
269     mq_msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_SEND, TR_MQ_PRIO_NORMAL);
270     msg_dup=talloc_strdup(mq_msg, msg); /* get local copy in mq_msg context */
271     tr_mq_msg_set_payload(mq_msg, msg_dup, NULL); /* no need for a free() func */
272     trpc_mq_add(trpc, mq_msg);
273     rc=TRP_SUCCESS;
274   }
275   talloc_free(tmp_ctx);
276   return rc;
277 }
278
279 /* Listens on all interfaces. Returns number of sockets opened. Their
280  * descriptors are stored in *fd_out, which should point to space for
281  * up to max_fd of them. */
282 static size_t trps_listen(TRPS_INSTANCE *trps, int port, int *fd_out, size_t max_fd) 
283 {
284   int rc = 0;
285   int conn = -1;
286   int optval=0;
287   struct addrinfo *ai=NULL;
288   struct addrinfo *ai_head=NULL;
289   struct addrinfo hints={.ai_flags=AI_PASSIVE,
290                          .ai_family=AF_UNSPEC,
291                          .ai_socktype=SOCK_STREAM,
292                          .ai_protocol=IPPROTO_TCP};
293   char *port_str=NULL;
294   size_t n_opened=0;
295
296   port_str=talloc_asprintf(NULL, "%d", port);
297   if (port_str==NULL) {
298     tr_debug("trps_listen: unable to allocate port.");
299     return -1;
300   }
301   getaddrinfo(NULL, port_str, &hints, &ai_head);
302   talloc_free(port_str);
303
304   for (ai=ai_head,n_opened=0; (ai!=NULL)&&(n_opened<max_fd); ai=ai->ai_next) {
305     if (0 > (conn = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol))) {
306       tr_debug("trps_listen: unable to open socket.");
307       continue;
308     }
309
310     optval=1;
311     if (0!=setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)))
312       tr_debug("trps_listen: unable to set SO_REUSEADDR."); /* not fatal? */
313
314     if (ai->ai_family==AF_INET6) {
315       /* don't allow IPv4-mapped IPv6 addresses (per RFC4942, not sure
316        * if still relevant) */
317       if (0!=setsockopt(conn, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval))) {
318         tr_debug("trps_listen: unable to set IPV6_V6ONLY. Skipping interface.");
319         close(conn);
320         continue;
321       }
322     }
323
324     rc=bind(conn, ai->ai_addr, ai->ai_addrlen);
325     if (rc<0) {
326       tr_debug("trps_listen: unable to bind to socket.");
327       close(conn);
328       continue;
329     }
330
331     if (0>listen(conn, 512)) {
332       tr_debug("trps_listen: unable to listen on bound socket.");
333       close(conn);
334       continue;
335     }
336
337     /* ok, this one worked. Save it */
338     fd_out[n_opened++]=conn;
339   }
340   freeaddrinfo(ai_head);
341
342   if (n_opened==0) {
343     tr_debug("trps_listen: no addresses available for listening.");
344     return -1;
345   }
346   
347   tr_debug("trps_listen: TRP Server listening on port %d on %d socket%s",
348            port,
349            n_opened,
350            (n_opened==1)?"":"s");
351
352   return n_opened;
353 }
354
355 /* get the currently selected route if available */
356 TRP_ROUTE *trps_get_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
357 {
358   return trp_rtable_get_entry(trps->rtable, comm, realm, peer);
359 }
360
361 TRP_ROUTE *trps_get_selected_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
362 {
363   tr_debug("trps_get_selected_route: entered. trps=%p, comm=%p, realm=%p", trps, comm, realm);
364   return trp_rtable_get_selected_entry(trps->rtable, comm, realm);
365 }
366
367 /* copy the result if you want to keep it */
368 TR_NAME *trps_get_next_hop(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
369 {
370   TRP_ROUTE *route=trps_get_selected_route(trps, comm, realm);
371   if (route==NULL)
372     return NULL;
373
374   return trp_route_get_next_hop(route);
375 }
376
377
378 /* mark a route as retracted */
379 static void trps_retract_route(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
380 {
381   trp_route_set_metric(entry, TRP_METRIC_INFINITY);
382   trp_route_set_triggered(entry, 1);
383 }
384
385 /* is this route retracted? */
386 static int trps_route_retracted(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
387 {
388   return (trp_metric_is_infinite(trp_route_get_metric(entry)));
389 }
390
391 static TRP_RC trps_read_message(TRPS_INSTANCE *trps, TRP_CONNECTION *conn, TR_MSG **msg)
392 {
393   int err=0;
394   char *buf=NULL;
395   size_t buflen = 0;
396   TRP_PEER *peer=NULL; /* entry in the peer table */
397   TR_NAME *conn_peer=NULL; /* name from the TRP_CONN, which comes from the gss context */
398
399   tr_debug("trps_read_message: started");
400   if (err = gsscon_read_encrypted_token(trp_connection_get_fd(conn),
401                                        *(trp_connection_get_gssctx(conn)), 
402                                        &buf,
403                                        &buflen)) {
404     tr_debug("trps_read_message: error");
405     if (buf)
406       free(buf);
407     return TRP_ERROR;
408   }
409
410   tr_debug("trps_read_message: message received, %u bytes.", (unsigned) buflen);
411   tr_debug("trps_read_message: %.*s", buflen, buf);
412
413   *msg=tr_msg_decode(buf, buflen);
414   free(buf);
415   if (*msg==NULL)
416     return TRP_NOPARSE;
417
418   conn_peer=trp_connection_get_peer(conn);
419   if (conn_peer==NULL) {
420     tr_err("trps_read_message: connection has no peer name");
421     return TRP_ERROR;
422   }
423
424   peer=trps_get_peer_by_gssname(trps, conn_peer);
425   if (peer==NULL) {
426     tr_err("trps_read_message: could not find peer with gssname=%s", trp_connection_get_gssname(conn));
427     return TRP_ERROR;
428   }
429
430   /* verify we received a message we support, otherwise drop it now */
431   switch (tr_msg_get_msg_type(*msg)) {
432   case TRP_UPDATE:
433     trp_upd_set_peer(tr_msg_get_trp_upd(*msg), tr_dup_name(conn_peer));
434     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 */
435     /* update provenance if necessary */
436     trp_upd_add_to_provenance(tr_msg_get_trp_upd(*msg), trp_peer_get_label(peer));
437     break;
438
439   case TRP_REQUEST:
440     trp_req_set_peer(tr_msg_get_trp_req(*msg), tr_dup_name(conn_peer));
441     break;
442
443   default:
444     tr_debug("trps_read_message: received unsupported message from %.*s", conn_peer->len, conn_peer->buf);
445     tr_msg_free_decoded(*msg);
446     *msg=NULL;
447     return TRP_UNSUPPORTED;
448   }
449   
450   return TRP_SUCCESS;
451 }
452
453 int trps_get_listener(TRPS_INSTANCE *trps,
454                       TRPS_MSG_FUNC msg_handler,
455                       TRP_AUTH_FUNC auth_handler,
456                       const char *hostname,
457                       unsigned int port,
458                       void *cookie,
459                       int *fd_out,
460                       size_t max_fd)
461 {
462   size_t n_fd=0;
463   size_t ii=0;
464
465   n_fd=trps_listen(trps, port, fd_out, max_fd);
466   if (n_fd==0)
467     tr_err("trps_get_listener: Error opening port %d.");
468   else {
469     /* opening port succeeded */
470     tr_info("trps_get_listener: Opened port %d.", port);
471     
472     /* make the sockets non-blocking */
473     for (ii=0; ii<n_fd; ii++) {
474       if (0 != fcntl(fd_out[ii], F_SETFL, O_NONBLOCK)) {
475         tr_err("trps_get_listener: Error setting O_NONBLOCK.");
476         for (ii=0; ii<n_fd; ii++) {
477           close(fd_out[ii]);
478           fd_out[ii]=-1;
479         }
480         n_fd=0;
481         break;
482       }
483     }
484   }
485
486   if (n_fd>0) {
487     /* store the caller's request handler & cookie */
488     trps->msg_handler = msg_handler;
489     trps->auth_handler = auth_handler;
490     trps->hostname = talloc_strdup(trps, hostname);
491     trps->port = port;
492     trps->cookie = cookie;
493   }
494
495   return n_fd;
496 }
497
498 TRP_RC trps_authorize_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
499 {
500   /* try to establish a GSS context */
501   if (0!=trp_connection_auth(conn, trps->auth_handler, trps->cookie)) {
502     tr_notice("trps_authorize_connection: failed to authorize connection");
503     trp_connection_close(conn);
504     return TRP_ERROR;
505   }
506   tr_notice("trps_authorize_connection: authorized connection");
507   return TRP_SUCCESS;
508 }
509
510 void trps_handle_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
511 {
512   TR_MSG *msg=NULL;
513   TRP_RC rc=TRP_ERROR;
514
515   /* loop as long as the connection exists */
516   while (trp_connection_get_status(conn)==TRP_CONNECTION_UP) {
517     rc=trps_read_message(trps, conn, &msg);
518     switch(rc) {
519     case TRP_SUCCESS:
520       trps->msg_handler(trps, conn, msg); /* send the TR_MSG off to the callback */
521       break;
522
523     case TRP_ERROR:
524       trp_connection_close(conn);
525       break;
526
527     default:
528       tr_debug("trps_handle_connection: trps_read_message failed (%d)", rc);
529     }
530   }
531
532   tr_debug("trps_handle_connection: connection closed.");
533 }
534
535 /* TODO: check realm/comm, now part of the update instead of inforec */
536 static TRP_RC trps_validate_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
537 {
538   if (upd==NULL) {
539     tr_notice("trps_validate_update: null TRP update.");
540     return TRP_BADARG;
541   }
542
543   if (trp_upd_get_realm(upd)==NULL) {
544     tr_notice("trps_validate_update: received TRP update without realm.");
545     return TRP_ERROR;
546   }
547
548   if (trp_upd_get_comm(upd)==NULL) {
549     tr_notice("trps_validate_update: received TRP update without community.");
550     return TRP_ERROR;
551   }
552
553   if (trp_upd_get_inforec(upd)==NULL) {
554     tr_notice("trps_validate_update: received TRP update with no info records.");
555     return TRP_ERROR;
556   }
557
558   if (trp_upd_get_peer(upd)==NULL) {
559     tr_notice("trps_validate_update: received TRP update without origin peer information.");
560     return TRP_ERROR;
561   }
562
563   
564   return TRP_SUCCESS;
565 }
566
567 /* ensure that the update could be accepted if feasible */
568 static TRP_RC trps_validate_inforec(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
569 {
570   switch(trp_inforec_get_type(rec)) {
571   case TRP_INFOREC_TYPE_ROUTE:
572     if ((trp_inforec_get_trust_router(rec)==NULL)
573        || (trp_inforec_get_next_hop(rec)==NULL)) {
574       tr_debug("trps_validate_inforec: missing record info.");
575       return TRP_ERROR;
576     }
577
578     /* check for valid metric */
579     if (trp_metric_is_invalid(trp_inforec_get_metric(rec))) {
580       tr_debug("trps_validate_inforec: invalid metric (%u).", trp_inforec_get_metric(rec));
581       return TRP_ERROR;
582     }
583
584     /* check for valid interval */
585     if (trp_inforec_get_interval(rec)==TRP_INTERVAL_INVALID) {
586       tr_debug("trps_validate_inforec: invalid interval.");
587       return TRP_ERROR;
588     }
589     break;
590
591   case TRP_INFOREC_TYPE_COMMUNITY:
592     /* TODO: validate community updates */
593     break;
594     
595   default:
596     tr_notice("trps_validate_inforec: unsupported record type.");
597     return TRP_UNSUPPORTED;
598   }
599
600   return TRP_SUCCESS;
601 }
602
603 /* link cost to a peer */
604 static unsigned int trps_cost(TRPS_INSTANCE *trps, TR_NAME *peer)
605 {
606   return 1;
607 }
608
609 static unsigned int trps_advertised_metric(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
610 {
611   TRP_ROUTE *entry=trp_rtable_get_entry(trps->rtable, comm, realm, peer);
612   if (entry==NULL)
613     return TRP_METRIC_INFINITY;
614   return trp_route_get_metric(entry) + trps_cost(trps, peer);
615 }
616
617 static int trps_check_feasibility(TRPS_INSTANCE *trps, TR_NAME *realm, TR_NAME *comm, TRP_INFOREC *rec)
618 {
619   unsigned int rec_metric=trp_inforec_get_metric(rec);
620   unsigned int new_metric=0;
621   unsigned int current_metric=0;
622   TR_NAME *next_hop=NULL;
623
624   /* we check these in the validation stage, but just in case... */
625   if (trp_metric_is_invalid(rec_metric))
626     return 0;
627
628   /* retractions (aka infinite metrics) are always feasible */
629   if (trp_metric_is_infinite(rec_metric))
630     return 1;
631
632   /* updates from our current next hop are always feasible*/
633   next_hop=trps_get_next_hop(trps, comm, realm);
634   if ((next_hop!=NULL)
635      && (0==tr_name_cmp(next_hop,trp_inforec_get_next_hop(rec)))) {
636     return 1;
637   }
638     
639
640   /* compare the existing metric we advertise to what we would advertise
641    * if we accept this update */
642   current_metric=trps_advertised_metric(trps, comm, realm, trp_inforec_get_next_hop(rec));
643   new_metric=rec_metric + trps_cost(trps, trp_inforec_get_next_hop(rec));
644   if (new_metric <= current_metric)
645     return 1;
646   else
647     return 0;
648 }
649
650 /* uses memory pointed to by *ts, also returns that value. On error, its contents are {0,0} */
651 static struct timespec *trps_compute_expiry(TRPS_INSTANCE *trps, unsigned int interval, struct timespec *ts)
652 {
653   const unsigned int small_factor=3; /* how many intervals we wait before expiring */
654   if (0!=clock_gettime(TRP_CLOCK, ts)) {
655     tr_err("trps_compute_expiry: could not read realtime clock.");
656     ts->tv_sec=0;
657     ts->tv_nsec=0;
658   }
659   tr_debug("trps_compute_expiry: tv_sec=%u, interval=%u, small_factor*interval=%u", ts->tv_sec, interval, small_factor*interval);
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 provenance 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 /**
1007  * Apply applicable TRP_INBOUND filters to an inforec. Rejects everything if peer has no filters.
1008  *
1009  * @param trps Active TRPS instance
1010  * @param upd TRP_UPD that contains the inforec to filter
1011  * @param rec Inforec to filter
1012  * @return 1 if accepted by the filter, 0 otherwise
1013  */
1014 static int trps_filter_inbound_inforec(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
1015 {
1016   TRP_PEER *peer=NULL;
1017   TR_NAME *peer_name=NULL;
1018   TR_FILTER_ACTION action=TR_FILTER_ACTION_REJECT;
1019   TR_FILTER_TARGET *target=NULL;
1020   int retval=0;
1021
1022   /* Look up the peer. For inbound messages, the peer is identified by its GSS name */
1023   peer_name=trp_upd_get_peer(upd);
1024   peer=trps_get_peer_by_gssname(trps, peer_name);
1025   if (peer==NULL) {
1026     tr_err("trps_filter_inbound_inforec: received inforec from unknown peer (%.*s), rejecting.",
1027            peer_name->len,
1028            peer_name->buf);
1029     return 0;
1030   }
1031
1032   /* tr_filter_apply() and tr_filter_set_get() handle null filter sets/filters by rejecting */
1033   target= tr_filter_target_trp_inforec(NULL, upd, rec);
1034   if (target==NULL) {
1035     /* TODO: signal that filtering failed. Until then, just filter everything and give an error message. */
1036     tr_crit("trps_filter_inbound_inforec: Unable to allocate filter target, cannot apply filter!");
1037   }
1038   if ((target==NULL)
1039       || (TR_FILTER_NO_MATCH==tr_filter_apply(target,
1040                                               tr_filter_set_get(peer->filters, TR_FILTER_TYPE_TRP_INBOUND),
1041                                               NULL,
1042                                               &action))
1043       || (action!=TR_FILTER_ACTION_ACCEPT)) {
1044     /* either the filter did not match or it matched a reject rule or allocating the target failed */
1045     retval=0;
1046   } else
1047     retval=1;
1048   if (target!=NULL)
1049     tr_filter_target_free(target);
1050
1051   /* filter matched an accept rule */
1052   return retval;
1053 }
1054
1055
1056 static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
1057 {
1058   TRP_INFOREC *rec=NULL;
1059
1060   if (trps_validate_update(trps, upd) != TRP_SUCCESS) {
1061     tr_notice("trps_handle_update: received invalid TRP update.");
1062     return TRP_ERROR;
1063   }
1064
1065   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
1066     /* validate/sanity check the record update */
1067     if (trps_validate_inforec(trps, rec) != TRP_SUCCESS) {
1068       tr_notice("trps_handle_update: invalid inforec in TRP update, discarding entire update.");
1069       return TRP_ERROR;
1070     }
1071   }
1072
1073   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
1074     if (!trps_filter_inbound_inforec(trps, upd, rec)) {
1075       tr_debug("trps_handle_update: inforec rejected by filter.");
1076       continue; /* just go on to the next record */
1077     }
1078
1079     switch (trp_inforec_get_type(rec)) {
1080     case TRP_INFOREC_TYPE_ROUTE:
1081       tr_debug("trps_handle_update: handling route inforec.");
1082       if (TRP_SUCCESS!=trps_handle_inforec_route(trps, upd, rec))
1083         tr_notice("trps_handle_update: error handling route inforec.");
1084       break;
1085     case TRP_INFOREC_TYPE_COMMUNITY:
1086       tr_debug("trps_handle_update: handling community inforec.");
1087       if (TRP_SUCCESS!=trps_handle_inforec_comm(trps, upd, rec))
1088         tr_notice("trps_handle_update: error handling community inforec.");
1089
1090       break;
1091     default:
1092       tr_notice("trps_handle_update: unsupported inforec in TRP update.");
1093       break;
1094     }
1095   }
1096   return TRP_SUCCESS;
1097 }
1098
1099 static TRP_RC trps_validate_request(TRPS_INSTANCE *trps, TRP_REQ *req)
1100 {
1101   if (req==NULL) {
1102     tr_notice("trps_validate_request: null TRP request.");
1103     return TRP_BADARG;
1104   }
1105
1106   if (trp_req_get_comm(req)==NULL) {
1107     tr_notice("trps_validate_request: received TRP request with null community.");
1108     return TRP_ERROR;
1109   }
1110   
1111   if (trp_req_get_realm(req)==NULL) {
1112     tr_notice("trps_validate_request: received TRP request with null realm.");
1113     return TRP_ERROR;
1114   }
1115   
1116   if (trp_req_get_peer(req)==NULL) {
1117     tr_notice("trps_validate_request: received TRP request without origin peer information.");
1118     return TRP_ERROR;
1119   }
1120   
1121   return TRP_SUCCESS;
1122 }
1123
1124 /* choose the best route to comm/realm, optionally excluding routes to a particular peer */
1125 static TRP_ROUTE *trps_find_best_route(TRPS_INSTANCE *trps,
1126                                         TR_NAME *comm,
1127                                         TR_NAME *realm,
1128                                         TR_NAME *exclude_peer)
1129 {
1130   TRP_ROUTE **entry=NULL;
1131   TRP_ROUTE *best=NULL;
1132   size_t n_entry=0;
1133   unsigned int kk=0;
1134   unsigned int kk_min=0;
1135   unsigned int min_metric=TRP_METRIC_INFINITY;
1136
1137   entry=trp_rtable_get_realm_entries(trps->rtable, comm, realm, &n_entry);
1138   for (kk=0; kk<n_entry; kk++) {
1139     if (trp_route_get_metric(entry[kk]) < min_metric) {
1140       if ((exclude_peer==NULL) || (0!=tr_name_cmp(trp_route_get_peer(entry[kk]),
1141                                                   exclude_peer))) {
1142         kk_min=kk;
1143         min_metric=trp_route_get_metric(entry[kk]);
1144       } 
1145     }
1146   }
1147   if (trp_metric_is_finite(min_metric))
1148     best=entry[kk_min];
1149   
1150   talloc_free(entry);
1151   return best;
1152 }
1153
1154 /* TODO: think this through more carefully. At least ought to add hysteresis
1155  * to avoid flapping between routers or routes. */
1156 TRP_RC trps_update_active_routes(TRPS_INSTANCE *trps)
1157 {
1158   size_t n_comm=0, ii=0;
1159   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
1160   size_t n_realm=0, jj=0;
1161   TR_NAME **realm=NULL;
1162   TRP_ROUTE *best_route=NULL, *cur_route=NULL;
1163   unsigned int best_metric=0, cur_metric=0;
1164
1165   for (ii=0; ii<n_comm; ii++) {
1166     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
1167     for (jj=0; jj<n_realm; jj++) {
1168       best_route=trps_find_best_route(trps, comm[ii], realm[jj], NULL);
1169       if (best_route==NULL)
1170         best_metric=TRP_METRIC_INFINITY;
1171       else
1172         best_metric=trp_route_get_metric(best_route);
1173
1174       cur_route=trps_get_selected_route(trps, comm[ii], realm[jj]);
1175       if (cur_route!=NULL) {
1176         cur_metric=trp_route_get_metric(cur_route);
1177         if ((best_metric < cur_metric) && (trp_metric_is_finite(best_metric))) {
1178           /* The new route has a lower metric than the previous, and is finite. Accept. */
1179           trp_route_set_selected(cur_route, 0);
1180           trp_route_set_selected(best_route, 1);
1181         } else if (!trp_metric_is_finite(cur_metric)) /* rejects infinite or invalid metrics */
1182           trp_route_set_selected(cur_route, 0);
1183       } else if (trp_metric_is_finite(best_metric)) {
1184         trp_route_set_selected(best_route, 1);
1185       }
1186     }
1187     if (realm!=NULL)
1188       talloc_free(realm);
1189     realm=NULL; n_realm=0;
1190   }
1191   if (comm!=NULL)
1192     talloc_free(comm);
1193   comm=NULL; n_comm=0;
1194
1195   return TRP_SUCCESS;
1196 }
1197
1198 /* true if curtime >= expiry */
1199 static int trps_expired(struct timespec *expiry, struct timespec *curtime)
1200 {
1201   return (tr_cmp_timespec(curtime, expiry) >= 0);
1202 }
1203
1204 /* Sweep for expired routes. For each expired route, if its metric is infinite, the route is flushed.
1205  * If its metric is finite, the metric is set to infinite and the route's expiration time is updated. */
1206 TRP_RC trps_sweep_routes(TRPS_INSTANCE *trps)
1207 {
1208   struct timespec sweep_time={0,0};
1209   TRP_ROUTE **entry=NULL;
1210   size_t n_entry=0;
1211   size_t ii=0;
1212
1213   /* use a single time for the entire sweep */
1214   if (0!=clock_gettime(TRP_CLOCK, &sweep_time)) {
1215     tr_err("trps_sweep_routes: could not read realtime clock.");
1216     sweep_time.tv_sec=0;
1217     sweep_time.tv_nsec=0;
1218     return TRP_ERROR;
1219   }
1220
1221   entry=trp_rtable_get_entries(trps->rtable, &n_entry); /* must talloc_free *entry */
1222
1223   /* loop over the entries */
1224   for (ii=0; ii<n_entry; ii++) {
1225     if (!trp_route_is_local(entry[ii]) && trps_expired(trp_route_get_expiry(entry[ii]), &sweep_time)) {
1226       tr_debug("trps_sweep_routes: route expired.");
1227       if (!trp_metric_is_finite(trp_route_get_metric(entry[ii]))) {
1228         /* flush route */
1229         tr_debug("trps_sweep_routes: metric was infinity, flushing route.");
1230         trp_rtable_remove(trps->rtable, entry[ii]); /* entry[ii] is no longer valid */
1231         entry[ii]=NULL;
1232       } else {
1233         /* set metric to infinity and reset timer */
1234         tr_debug("trps_sweep_routes: setting metric to infinity and resetting expiry.");
1235         trp_route_set_metric(entry[ii], TRP_METRIC_INFINITY);
1236         trp_route_set_expiry(entry[ii], trps_compute_expiry(trps,
1237                                                              trp_route_get_interval(entry[ii]),
1238                                                              trp_route_get_expiry(entry[ii])));
1239       }
1240     }
1241   }
1242
1243   talloc_free(entry);
1244   return TRP_SUCCESS;
1245 }
1246
1247
1248 static char *timespec_to_str(struct timespec *ts)
1249 {
1250   struct tm tm;
1251   char *s=NULL;
1252
1253   if (localtime_r(&(ts->tv_sec), &tm)==NULL)
1254     return NULL;
1255
1256   s=malloc(40); /* long enough to contain strftime result */
1257   if (s==NULL)
1258     return NULL;
1259
1260   if (strftime(s, 40, "%F %T", &tm)==0) {
1261     free(s);
1262     return NULL;
1263   }
1264   return s;
1265 }
1266
1267
1268 /* Sweep for expired communities/realms/memberships. */
1269 TRP_RC trps_sweep_ctable(TRPS_INSTANCE *trps)
1270 {
1271   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1272   struct timespec sweep_time={0,0};
1273   TR_COMM_MEMB *memb=NULL;
1274   TR_COMM_ITER *iter=NULL;
1275   TRP_RC rc=TRP_ERROR;
1276
1277   /* use a single time for the entire sweep */
1278   if (0!=clock_gettime(TRP_CLOCK, &sweep_time)) {
1279     tr_err("trps_sweep_ctable: could not read realtime clock.");
1280     sweep_time.tv_sec=0;
1281     sweep_time.tv_nsec=0;
1282     goto cleanup;
1283   }
1284
1285   /* iterate all memberships */
1286   iter=tr_comm_iter_new(tmp_ctx);
1287   if (iter==NULL) {
1288     tr_err("trps_sweep_ctable: unable to allocate iterator.");
1289     rc=TRP_NOMEM;
1290     goto cleanup;
1291   }
1292   for (memb=tr_comm_memb_iter_all_first(iter, trps->ctable);
1293        memb!=NULL;
1294        memb=tr_comm_memb_iter_all_next(iter)) {
1295     if (tr_comm_memb_get_origin(memb)==NULL)
1296       continue; /* do not expire local entries */
1297
1298     if (tr_comm_memb_is_expired(memb, &sweep_time)) {
1299       if (tr_comm_memb_get_times_expired(memb)>0) {
1300         /* Already expired once; flush. */
1301         tr_debug("trps_sweep_ctable: flushing expired community membership (%.*s in %.*s, origin %.*s, expired %s).",
1302                  tr_comm_memb_get_realm_id(memb)->len, tr_comm_memb_get_realm_id(memb)->buf,
1303                  tr_comm_get_id(tr_comm_memb_get_comm(memb))->len, tr_comm_get_id(tr_comm_memb_get_comm(memb))->buf,
1304                  tr_comm_memb_get_origin(memb)->len, tr_comm_memb_get_origin(memb)->buf,
1305                  timespec_to_str(tr_comm_memb_get_expiry(memb)));
1306         tr_comm_table_remove_memb(trps->ctable, memb);
1307         tr_comm_memb_free(memb);
1308       } else {
1309         /* This is the first expiration. Note this and reset the expiry time. */
1310         tr_comm_memb_expire(memb);
1311         trps_compute_expiry(trps, tr_comm_memb_get_interval(memb), tr_comm_memb_get_expiry(memb));
1312         tr_debug("trps_sweep_ctable: community membership expired at %s, resetting expiry to %s (%.*s in %.*s, origin %.*s).",
1313                  timespec_to_str(&sweep_time),
1314                  timespec_to_str(tr_comm_memb_get_expiry(memb)),
1315                  tr_comm_memb_get_realm_id(memb)->len, tr_comm_memb_get_realm_id(memb)->buf,
1316                  tr_comm_get_id(tr_comm_memb_get_comm(memb))->len, tr_comm_get_id(tr_comm_memb_get_comm(memb))->buf,
1317                  tr_comm_memb_get_origin(memb)->len, tr_comm_memb_get_origin(memb)->buf);
1318       }
1319     }
1320   }
1321
1322   /* get rid of any unreferenced realms, etc */
1323   tr_comm_table_sweep(trps->ctable);
1324
1325 cleanup:
1326   talloc_free(tmp_ctx);
1327   return rc;
1328 }
1329
1330 /* add metrics */
1331 static unsigned int trps_metric_add(unsigned int m1, unsigned int m2)
1332 {
1333   if (trp_metric_is_invalid(m1) || trp_metric_is_invalid(m2))
1334     return TRP_METRIC_INVALID;
1335
1336   if (trp_metric_is_infinite(m1) || trp_metric_is_infinite(m2))
1337     return TRP_METRIC_INFINITY;
1338
1339   if (trp_metric_is_finite(m1+m2))
1340     return m1+m2;
1341   else
1342     return TRP_METRIC_INFINITY;
1343 }
1344
1345 /* convert an rentry into a new trp update info record */
1346 static TRP_INFOREC *trps_route_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
1347 {
1348   TRP_INFOREC *rec=trp_inforec_new(mem_ctx, TRP_INFOREC_TYPE_ROUTE);
1349   unsigned int linkcost=0;
1350
1351   if (rec!=NULL) {
1352     if (trp_route_is_local(route))
1353       linkcost=0;
1354     else {
1355       linkcost=trp_peer_get_linkcost(trps_get_peer_by_gssname(trps,
1356                                                               trp_route_get_peer(route)));
1357     }
1358
1359     /* Note that we leave the next hop empty since the recipient fills that in.
1360      * This is where we add the link cost (currently always 1) to the next peer. */
1361     if ((trp_inforec_set_trust_router(rec, trp_route_dup_trust_router(route)) != TRP_SUCCESS)
1362        ||(trp_inforec_set_metric(rec,
1363                                  trps_metric_add(trp_route_get_metric(route),
1364                                                  linkcost)) != TRP_SUCCESS)
1365        ||(trp_inforec_set_interval(rec, trps_get_update_interval(trps)) != TRP_SUCCESS)) {
1366       tr_err("trps_route_to_inforec: error creating route update.");
1367       talloc_free(rec);
1368       rec=NULL;
1369     }
1370   }
1371   return rec;
1372 }
1373
1374 static TRP_UPD *trps_route_to_upd(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
1375 {
1376   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1377   TRP_UPD *upd=trp_upd_new(tmp_ctx);
1378   TRP_INFOREC *rec=NULL;
1379
1380   if (upd==NULL) {
1381     tr_err("trps_route_to_upd: could not create update message.");
1382     goto cleanup;
1383   }
1384   trp_upd_set_realm(upd, trp_route_dup_realm(route));
1385   if (trp_upd_get_realm(upd)==NULL) {
1386     tr_err("trps_route_to_upd: could not copy realm.");
1387     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
1388     goto cleanup;
1389   }
1390   trp_upd_set_comm(upd, trp_route_dup_comm(route));
1391   if (trp_upd_get_comm(upd)==NULL) {
1392     tr_err("trps_route_to_upd: could not copy comm.");
1393     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
1394     goto cleanup;
1395   }
1396   rec=trps_route_to_inforec(tmp_ctx, trps, route);
1397   if (rec==NULL) {
1398     tr_err("trps_route_to_upd: could not create route info record for realm %.*s in comm %.*s.",
1399            trp_route_get_realm(route)->len, trp_route_get_realm(route)->buf,
1400            trp_route_get_comm(route)->len, trp_route_get_comm(route)->buf);
1401     upd=NULL; /* it's till in tmp_ctx, so it will be freed */
1402     goto cleanup;
1403   }
1404   trp_upd_add_inforec(upd, rec);
1405
1406   /* sucess */
1407   talloc_steal(mem_ctx, upd);
1408
1409 cleanup:
1410   talloc_free(tmp_ctx);
1411   return upd;
1412 }
1413
1414 /* select the correct route to comm/realm to be announced to peer */
1415 static TRP_ROUTE *trps_select_realm_update(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer_gssname)
1416 {
1417   TRP_ROUTE *route;
1418
1419   /* Take the currently selected route unless it is through the peer we're sending the update to.
1420    * I.e., enforce the split horizon rule. */
1421   route=trp_rtable_get_selected_entry(trps->rtable, comm, realm);
1422   if (route==NULL) {
1423     /* No selected route, this should only happen if the only route has been retracted,
1424      * in which case we do not want to advertise it. */
1425     return NULL;
1426   }
1427   tr_debug("trps_select_realm_update: %s vs %s", peer_gssname->buf,
1428            trp_route_get_peer(route)->buf);
1429   if (0==tr_name_cmp(peer_gssname, trp_route_get_peer(route))) {
1430     tr_debug("trps_select_realm_update: matched, finding alternate route");
1431     /* the selected entry goes through the peer we're reporting to, choose an alternate */
1432     route=trps_find_best_route(trps, comm, realm, peer_gssname);
1433     if ((route==NULL) || (!trp_metric_is_finite(trp_route_get_metric(route))))
1434       return NULL; /* don't advertise a nonexistent or retracted route */
1435   }
1436   return route;
1437 }
1438
1439 /* Add TRP_UPD msgs to the updates GPtrArray. Caller needs to arrange for these to be freed. */
1440 static TRP_RC trps_select_route_updates_for_peer(TALLOC_CTX *mem_ctx,
1441                                                  GPtrArray *updates,
1442                                                  TRPS_INSTANCE *trps,
1443                                                  TR_NAME *peer_gssname,
1444                                                  int triggered)
1445 {
1446   size_t n_comm=0;
1447   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
1448   TR_NAME **realm=NULL;
1449   size_t n_realm=0;
1450   size_t ii=0, jj=0;
1451   TRP_ROUTE *best=NULL;
1452   TRP_UPD *upd=NULL;
1453
1454   if (updates==NULL)
1455     return TRP_BADARG;
1456
1457   for (ii=0; ii<n_comm; ii++) {
1458     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
1459     for (jj=0; jj<n_realm; jj++) {
1460       best=trps_select_realm_update(trps, comm[ii], realm[jj], peer_gssname);
1461       /* If we found a route, add it to the list. If triggered!=0, then only
1462        * add triggered routes. */
1463       if ((best!=NULL) && ((!triggered) || trp_route_is_triggered(best))) {
1464         upd=trps_route_to_upd(mem_ctx, trps, best);
1465         if (upd==NULL) {
1466           tr_err("trps_select_route_updates_for_peer: unable to create update message.");
1467           continue;
1468         }
1469         g_ptr_array_add(updates, upd);
1470       }
1471     }
1472     
1473     if (realm!=NULL)
1474       talloc_free(realm);
1475     realm=NULL;
1476     n_realm=0;
1477   }
1478
1479   if (comm!=NULL)
1480     talloc_free(comm);
1481   
1482   return TRP_SUCCESS;
1483 }
1484
1485 static TRP_INFOREC *trps_memb_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_COMM_MEMB *memb)
1486 {
1487   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1488   TRP_INFOREC *rec=NULL;
1489   TR_COMM *comm=NULL;
1490
1491   if (memb==NULL)
1492     goto cleanup;
1493
1494   comm=tr_comm_memb_get_comm(memb);
1495   rec=trp_inforec_new(tmp_ctx, TRP_INFOREC_TYPE_COMMUNITY);
1496   if (rec==NULL)
1497     goto cleanup;
1498   
1499   if (TRP_SUCCESS!=trp_inforec_set_comm_type(rec, tr_comm_get_type(comm))) {
1500     rec=NULL;
1501     goto cleanup;
1502   }
1503   
1504   if (TRP_SUCCESS!=trp_inforec_set_role(rec, tr_comm_memb_get_role(memb))) {
1505     rec=NULL;
1506     goto cleanup;
1507   }
1508
1509   if ((NULL!=tr_comm_get_apcs(comm)) &&
1510       ( (TRP_SUCCESS!=trp_inforec_set_apcs(rec,
1511                                            tr_apc_dup(rec, tr_comm_get_apcs(comm)))) ||
1512         (NULL==trp_inforec_get_apcs(rec)))) {
1513     rec=NULL;
1514     goto cleanup;
1515   }
1516
1517   if ((NULL!=tr_comm_get_owner_realm(comm)) &&
1518       ( (TRP_SUCCESS!=trp_inforec_set_owner_realm(rec, tr_dup_name(tr_comm_get_owner_realm(comm)))) ||
1519         (NULL==trp_inforec_get_owner_realm(rec)))) {
1520     rec=NULL;
1521     goto cleanup;
1522   }
1523
1524   if ((NULL!=tr_comm_get_owner_contact(comm)) &&
1525       ( (TRP_SUCCESS!=trp_inforec_set_owner_contact(rec, tr_dup_name(tr_comm_get_owner_contact(comm)))) ||
1526         (NULL==trp_inforec_get_owner_contact(rec)))) {
1527     rec=NULL;
1528     goto cleanup;
1529   }
1530
1531   if ((NULL!=tr_comm_memb_get_provenance(memb)) &&
1532       (TRP_SUCCESS!=trp_inforec_set_provenance(rec, tr_comm_memb_get_provenance(memb)))) {
1533     rec=NULL;
1534     goto cleanup;
1535   }
1536
1537   if (TRP_SUCCESS!=trp_inforec_set_interval(rec, trps_get_update_interval(trps))) {
1538     rec=NULL;
1539     goto cleanup;
1540   }
1541
1542   /* success! */
1543   talloc_steal(mem_ctx, rec);
1544
1545 cleanup:
1546   talloc_free(tmp_ctx);
1547   return rec;
1548 }
1549
1550 /* construct an update with all the inforecs for comm/realm/role to be sent to peer */
1551 static TRP_UPD *trps_comm_update(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_NAME *peer_gssname, TR_COMM *comm, TR_REALM *realm)
1552 {
1553   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1554   TRP_UPD *upd=trp_upd_new(tmp_ctx);
1555   TRP_INFOREC *rec=NULL;
1556   TR_COMM_ITER *iter=NULL;
1557   TR_COMM_MEMB *memb=NULL;
1558
1559   if (upd==NULL)
1560     goto cleanup;
1561   
1562   trp_upd_set_comm(upd, tr_comm_dup_id(comm));
1563   trp_upd_set_realm(upd, tr_realm_dup_id(realm));
1564   /* leave peer empty */
1565
1566   iter=tr_comm_iter_new(tmp_ctx);
1567   if (iter==NULL) {
1568     tr_err("trps_comm_update: unable to allocate iterator.");
1569     upd=NULL;
1570     goto cleanup;
1571   }
1572   
1573   /* now add inforecs */
1574   switch (realm->role) {
1575   case TR_ROLE_IDP:
1576     memb=tr_comm_table_find_idp_memb(trps->ctable,
1577                                      tr_realm_get_id(realm),
1578                                      tr_comm_get_id(comm));
1579     break;
1580   case TR_ROLE_RP:
1581     memb=tr_comm_table_find_rp_memb(trps->ctable,
1582                                     tr_realm_get_id(realm),
1583                                     tr_comm_get_id(comm));
1584     break;
1585   default:
1586     break;
1587   }
1588   if (memb!=NULL) {
1589     for (memb=tr_comm_memb_iter_first(iter, memb);
1590          memb!=NULL;
1591          memb=tr_comm_memb_iter_next(iter)) {
1592       rec=trps_memb_to_inforec(tmp_ctx, trps, memb);
1593       if (rec==NULL) {
1594         tr_err("trps_comm_update: unable to allocate inforec.");
1595         upd=NULL;
1596         goto cleanup;
1597       }
1598       trp_upd_add_inforec(upd, rec);
1599     }
1600   }
1601
1602   if (trp_upd_get_inforec(upd)==NULL)
1603     upd=NULL; /* no inforecs, no reason to send the update */
1604   else
1605     talloc_steal(mem_ctx, upd); /* success! */
1606
1607 cleanup:
1608   talloc_free(tmp_ctx);
1609   return upd;
1610 }
1611
1612 /* Find all community updates to send to a peer and add these as TR_UPD records
1613  * to the updates GPtrArray. */
1614 static TRP_RC trps_select_comm_updates_for_peer(TALLOC_CTX *mem_ctx,
1615                                                 GPtrArray *updates,
1616                                                 TRPS_INSTANCE *trps,
1617                                                 TR_NAME *peer_gssname,
1618                                                 int triggered)
1619 {
1620   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1621   TR_COMM_ITER *comm_iter=NULL;
1622   TR_COMM *comm=NULL;
1623   TR_COMM_ITER *realm_iter=NULL;
1624   TR_REALM *realm=NULL;
1625   TRP_UPD *upd=NULL;
1626   TRP_RC rc=TRP_ERROR;
1627
1628   /* currently do not send any communities on triggered updates */
1629   if (triggered) {
1630     rc=TRP_SUCCESS;
1631     goto cleanup;
1632   }
1633
1634   comm_iter=tr_comm_iter_new(tmp_ctx);
1635   realm_iter=tr_comm_iter_new(tmp_ctx);
1636   if ((comm_iter==NULL) || (realm_iter==NULL)) {
1637     tr_err("trps_select_comm_updates_for_peer: unable to allocate iterator.");
1638     rc=TRP_NOMEM;
1639     goto cleanup;
1640   }
1641
1642   /* do every community */
1643   for (comm=tr_comm_table_iter_first(comm_iter, trps->ctable);
1644        comm!=NULL;
1645        comm=tr_comm_table_iter_next(comm_iter)) {
1646     /* do every realm in this community */
1647     tr_debug("trps_select_comm_updates_for_peer: looking through community %.*s",
1648              tr_comm_get_id(comm)->len,
1649              tr_comm_get_id(comm)->buf);
1650     for (realm=tr_realm_iter_first(realm_iter, trps->ctable, tr_comm_get_id(comm));
1651          realm!=NULL;
1652          realm=tr_realm_iter_next(realm_iter)) {
1653       /* get the update for this comm/realm */
1654       tr_debug("trps_select_comm_updates_for_peer: adding realm %.*s",
1655                tr_realm_get_id(realm)->len,
1656                tr_realm_get_id(realm)->buf);
1657       upd=trps_comm_update(mem_ctx, trps, peer_gssname, comm, realm);
1658       if (upd!=NULL)
1659         g_ptr_array_add(updates, upd);
1660     }
1661   }
1662
1663 cleanup:
1664   talloc_free(tmp_ctx);
1665   return rc;
1666 }
1667
1668 /**
1669  * Filter the inforecs in a single update
1670  *
1671  * @param filt The filter to apply
1672  * @param upd The update to filter
1673  */
1674 static void trps_filter_one_outbound_update(TR_FILTER *filt, TRP_UPD *upd)
1675 {
1676   TRP_INFOREC *this=NULL, *next=NULL;
1677   TR_FILTER_ACTION action=TR_FILTER_ACTION_REJECT;
1678   TR_FILTER_TARGET *target=NULL;
1679
1680   for(this=trp_upd_get_inforec(upd); this!=NULL; this=next) {
1681     next=this->next;
1682     target= tr_filter_target_trp_inforec(NULL, upd, this);
1683     if (target==NULL) {
1684       /* TODO: signal that filtering failed. Until then, just filter everything and give an error message. */
1685       tr_crit("trps_filter_one_outbound_update: Unable to allocate filter target, cannot apply filter!");
1686     }
1687     if ((target==NULL)
1688         || (TR_FILTER_NO_MATCH==tr_filter_apply(target, filt, NULL, &action))
1689         || (action!=TR_FILTER_ACTION_ACCEPT)) {
1690       /* Either no filter matched or one matched and rejected this record.
1691        * Also filter out record if we were unable to allocate a target. */
1692       trp_upd_remove_inforec(upd, this); /* "this" is now invalid */
1693     }
1694     if (target!=NULL)
1695       tr_filter_target_free(target);
1696   }
1697 }
1698
1699 /**
1700  * May shuffle the update list.
1701  *
1702  * @param filters The filter set for the relevant TRP peer
1703  * @param updates GPtrArray of updates to filter
1704  */
1705 static void trps_filter_outbound_updates(TR_FILTER_SET *filters, GPtrArray *updates)
1706 {
1707   TRP_UPD *upd=NULL;
1708   guint ii=0;
1709
1710   /* Walk backward through the array so we can remove elements. Careful about loop
1711    * termination - remember that ii is unsigned. */
1712   for (ii=updates->len; ii>0; ii--) {
1713     upd=g_ptr_array_index(updates, ii-1);
1714     trps_filter_one_outbound_update(tr_filter_set_get(filters, TR_FILTER_TYPE_TRP_OUTBOUND), upd);
1715     /* see if we removed all the records from this update */
1716     if (trp_upd_num_inforecs(upd)==0)
1717       g_ptr_array_remove_index_fast(updates, ii-1); /* does not preserve order at index ii or higher */
1718   }
1719 }
1720
1721 /* helper for trps_update_one_peer. Frees the TRP_UPD pointed to by a GPtrArray element */
1722 static void trps_trp_upd_destroy(gpointer data)
1723 {
1724   trp_upd_free((TRP_UPD *)data);
1725 }
1726
1727 /* all routes/communities to a single peer, unless comm/realm are specified (both or neither must be NULL) */
1728 static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
1729                                    TRP_PEER *peer,
1730                                    TRP_UPDATE_TYPE update_type,
1731                                    TR_NAME *realm,
1732                                    TR_NAME *comm)
1733 {
1734   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1735   TR_MSG msg; /* not a pointer! */
1736   TRP_UPD *upd=NULL;
1737   TRP_ROUTE *route=NULL;
1738   size_t ii=0;
1739   char *encoded=NULL;
1740   TRP_RC rc=TRP_ERROR;
1741   TR_NAME *peer_label=trp_peer_get_label(peer);
1742   GPtrArray *updates=g_ptr_array_new_with_free_func(trps_trp_upd_destroy);
1743
1744   if (updates==NULL) {
1745     tr_err("trps_update_one_peer: unable to allocate updates array.");
1746     rc=TRP_NOMEM;
1747     goto cleanup;
1748   }
1749
1750   switch (update_type) {
1751   case TRP_UPDATE_TRIGGERED:
1752     tr_debug("trps_update_one_peer: preparing triggered update for %.*s",
1753              peer_label->len, peer_label->buf);
1754     break;
1755   case TRP_UPDATE_SCHEDULED:
1756     tr_debug("trps_update_one_peer: preparing scheduled update for %.*s",
1757              peer_label->len, peer_label->buf);
1758     break;
1759   case TRP_UPDATE_REQUESTED:
1760     tr_debug("trps_update_one_peer: preparing requested update for %.*s",
1761              peer_label->len, peer_label->buf);
1762     break;
1763   default:
1764     tr_err("trps_update_one_peer: invalid update type requested.");
1765     rc=TRP_BADARG;
1766     goto cleanup;
1767   }
1768
1769   /* First, gather route updates. */
1770   tr_debug("trps_update_one_peer: selecting route updates for %.*s.", peer_label->len, peer_label->buf);
1771   if ((comm==NULL) && (realm==NULL)) {
1772     /* do all realms */
1773     rc=trps_select_route_updates_for_peer(tmp_ctx,
1774                                           updates,
1775                                           trps,
1776                                           peer_label,
1777                                           update_type==TRP_UPDATE_TRIGGERED);
1778   } else if ((comm!=NULL) && (realm!=NULL)) {
1779     /* a single community/realm was requested */
1780     route=trps_select_realm_update(trps, comm, realm, peer_label);
1781     if (route==NULL) {
1782       /* we have no actual update to send back, MUST send a retraction */
1783       tr_debug("trps_update_one_peer: community/realm without route requested, sending mandatory retraction.");
1784       route=trp_route_new(tmp_ctx);
1785       trp_route_set_comm(route, tr_dup_name(comm));
1786       trp_route_set_realm(route, tr_dup_name(realm));
1787       trp_route_set_peer(route, tr_new_name(""));
1788       trp_route_set_metric(route, TRP_METRIC_INFINITY);
1789       trp_route_set_trust_router(route, tr_new_name(""));
1790       trp_route_set_next_hop(route, tr_new_name(""));
1791     }
1792     upd=trps_route_to_upd(tmp_ctx, trps, route);
1793     if (upd==NULL) {
1794       tr_err("trps_update_one_peer: unable to allocate route update.");
1795       rc=TRP_NOMEM;
1796       goto cleanup;
1797     }
1798     g_ptr_array_add(updates, upd);
1799   } else {
1800     tr_err("trps_update_one_peer: error: only comm or realm was specified. Need both or neither.");
1801     rc=TRP_ERROR;
1802     goto cleanup;
1803   }
1804
1805   /* Second, gather community updates */
1806   tr_debug("trps_update_one_peer: selecting community updates for %.*s.", peer_label->len, peer_label->buf);
1807   rc=trps_select_comm_updates_for_peer(tmp_ctx, updates, trps, peer_label, update_type==TRP_UPDATE_TRIGGERED);
1808
1809   /* see if we have anything to send */
1810   if (updates->len<=0)
1811     tr_debug("trps_update_one_peer: no updates for %.*s", peer_label->len, peer_label->buf);
1812   else {
1813     /* Apply outbound TRP filters for this peer */
1814     trps_filter_outbound_updates(peer->filters, updates);
1815
1816     if (updates->len<=0)
1817       tr_debug("trps_update_one_peer: no updates for %.*s after filtering.", peer_label->len, peer_label->buf);
1818     else {
1819       tr_debug("trps_update_one_peer: sending %d update messages.", updates->len);
1820       for (ii=0; ii<updates->len; ii++) {
1821         upd = (TRP_UPD *) g_ptr_array_index(updates, ii);
1822         /* now encode the update message */
1823         tr_msg_set_trp_upd(&msg, upd);
1824         encoded = tr_msg_encode(&msg);
1825         if (encoded == NULL) {
1826           tr_err("trps_update_one_peer: error encoding update.");
1827           rc = TRP_ERROR;
1828           goto cleanup;
1829         }
1830
1831         tr_debug("trps_update_one_peer: adding message to queue.");
1832         if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
1833           tr_err("trps_update_one_peer: error queueing update.");
1834         else
1835           tr_debug("trps_update_one_peer: update queued successfully.");
1836
1837         tr_msg_free_encoded(encoded);
1838         encoded = NULL;
1839       }
1840     }
1841   }
1842
1843   rc=TRP_SUCCESS;
1844
1845 cleanup:
1846   if (updates!=NULL)
1847     g_ptr_array_free(updates, TRUE); /* frees any TRP_UPD records */
1848   talloc_free(tmp_ctx);
1849   return rc;
1850 }
1851
1852 /* all routes/communities to all peers */
1853 TRP_RC trps_update(TRPS_INSTANCE *trps, TRP_UPDATE_TYPE update_type)
1854 {
1855   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1856   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
1857   TRP_PEER *peer=NULL;
1858   TRP_RC rc=TRP_SUCCESS;
1859
1860   if (trps->ptable==NULL)
1861     return TRP_SUCCESS; /* no peers, nothing to do */
1862
1863   if (iter==NULL) {
1864     tr_err("trps_update: failed to allocate peer table iterator.");
1865     talloc_free(tmp_ctx);
1866     return TRP_NOMEM;
1867   }
1868
1869   for (peer=trp_ptable_iter_first(iter, trps->ptable);
1870        (peer!=NULL) && (rc==TRP_SUCCESS);
1871        peer=trp_ptable_iter_next(iter))
1872   {
1873     if (!trps_peer_connected(trps, peer)) {
1874       TR_NAME *peer_label=trp_peer_get_label(peer);
1875       tr_debug("trps_update: no TRP connection to %.*s, skipping.",
1876                peer_label->len, peer_label->buf);
1877       continue;
1878     }
1879     rc=trps_update_one_peer(trps, peer, update_type, NULL, NULL);
1880   }
1881
1882   tr_debug("trps_update: rc=%u after attempting update.", rc);
1883   trp_ptable_iter_free(iter);
1884   trp_rtable_clear_triggered(trps->rtable); /* don't re-send triggered updates */
1885   talloc_free(tmp_ctx);
1886   return rc;
1887 }        
1888
1889 TRP_RC trps_add_route(TRPS_INSTANCE *trps, TRP_ROUTE *route)
1890 {
1891   trp_rtable_add(trps->rtable, route); /* should return status */
1892   return TRP_SUCCESS; 
1893 }
1894
1895 /* steals the peer object */
1896 TRP_RC trps_add_peer(TRPS_INSTANCE *trps, TRP_PEER *peer)
1897 {
1898   if (trps->ptable==NULL) {
1899     trps->ptable=trp_ptable_new(trps);
1900     if (trps->ptable==NULL)
1901       return TRP_NOMEM;
1902   }
1903   return trp_ptable_add(trps->ptable, peer);
1904 }
1905
1906 TRP_PEER *trps_get_peer_by_gssname(TRPS_INSTANCE *trps, TR_NAME *gssname)
1907 {
1908   if (trps->ptable==NULL)
1909     return NULL;
1910
1911   return trp_ptable_find_gss_name(trps->ptable, gssname);
1912 }
1913
1914 TRP_PEER *trps_get_peer_by_servicename(TRPS_INSTANCE *trps, TR_NAME *servicename)
1915 {
1916   if (trps->ptable==NULL)
1917     return NULL;
1918
1919   return trp_ptable_find_servicename(trps->ptable, servicename);
1920 }
1921
1922 int trps_peer_connected(TRPS_INSTANCE *trps, TRP_PEER *peer)
1923 {
1924   TRPC_INSTANCE *trpc=trps_find_trpc(trps, peer);
1925   if (trpc==NULL)
1926     return 0;
1927
1928   if (trpc_get_status(trpc)==TRP_CONNECTION_UP)
1929     return 1;
1930   else
1931     return 0;
1932 }
1933
1934
1935 static TRP_RC trps_handle_request(TRPS_INSTANCE *trps, TRP_REQ *req)
1936 {
1937   TR_NAME *comm=NULL;
1938   TR_NAME *realm=NULL;
1939
1940   tr_debug("trps_handle_request: handling TRP request.");
1941
1942   if (trps_validate_request(trps, req) != TRP_SUCCESS) {
1943     tr_notice("trps_handle_request: received invalid TRP request.");
1944     return TRP_ERROR;
1945   }
1946
1947   if (!trp_req_is_wildcard(req)) {
1948     comm=trp_req_get_comm(req);
1949     realm=trp_req_get_realm(req);
1950     tr_debug("trps_handle_request: route for %.*s/%.*s requested.",
1951              comm->len, comm->buf, realm->len, realm->buf);
1952   } else {
1953     tr_debug("trps_handle_request: all routes requested.");
1954     /* leave comm/realm NULL */
1955   }
1956   return trps_update_one_peer(trps,
1957                               trps_get_peer_by_gssname(trps, trp_req_get_peer(req)),
1958                               TRP_UPDATE_REQUESTED,
1959                               realm,
1960                               comm);
1961 }
1962
1963
1964 TRP_RC trps_handle_tr_msg(TRPS_INSTANCE *trps, TR_MSG *tr_msg)
1965 {
1966   TRP_RC rc=TRP_ERROR;
1967
1968   switch (tr_msg_get_msg_type(tr_msg)) {
1969   case TRP_UPDATE:
1970     rc=trps_handle_update(trps, tr_msg_get_trp_upd(tr_msg));
1971     if (rc==TRP_SUCCESS) {
1972       rc=trps_update_active_routes(trps);
1973       trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
1974     }
1975     return rc;
1976
1977   case TRP_REQUEST:
1978     rc=trps_handle_request(trps, tr_msg_get_trp_req(tr_msg));
1979     return rc;
1980
1981   default:
1982     /* unknown error or one we don't care about (e.g., TID messages) */
1983     return TRP_ERROR;
1984   }
1985 }
1986
1987 /* send wildcard route request to a peer */
1988 TRP_RC trps_wildcard_route_req(TRPS_INSTANCE *trps, TR_NAME *peer_servicename)
1989 {
1990   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1991   TRP_PEER *peer=trps_get_peer_by_servicename(trps, peer_servicename);
1992   TR_MSG msg; /* not a pointer */
1993   TRP_REQ *req=trp_req_new(tmp_ctx);
1994   char *encoded=NULL;
1995   TRP_RC rc=TRP_ERROR;
1996
1997   if (peer==NULL) {
1998     tr_err("trps_wildcard_route_req: unknown peer (%.*s).", peer_servicename->len, peer_servicename->buf);
1999     rc=TRP_BADARG;
2000     goto cleanup;
2001   }
2002   if ((req==NULL) || (trp_req_make_wildcard(req)!=TRP_SUCCESS)) {
2003     tr_err("trps_wildcard_route_req: unable to create wildcard TRP request.");
2004     rc=TRP_NOMEM;
2005     goto cleanup;
2006   }
2007
2008   tr_msg_set_trp_req(&msg, req);
2009   encoded=tr_msg_encode(&msg);
2010   if (encoded==NULL) {
2011     tr_err("trps_wildcard_route_req: error encoding wildcard TRP request.");
2012     rc=TRP_ERROR;
2013     goto cleanup;
2014   }
2015
2016   tr_debug("trps_wildcard_route_req: adding message to queue.");
2017   if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS) {
2018     tr_err("trps_wildcard_route_req: error queueing request.");
2019     rc=TRP_ERROR;
2020   } else {
2021     tr_debug("trps_wildcard_route_req: request queued successfully.");
2022     rc=TRP_SUCCESS;
2023   }
2024
2025 cleanup:
2026   if (encoded!=NULL)
2027     tr_msg_free_encoded(encoded);
2028   if (req!=NULL)
2029     trp_req_free(req);
2030
2031   talloc_free(tmp_ctx);
2032   return rc;
2033 }