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