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