Fix segfault issues. Comm updates now sent, but ignored.
[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
42 #include <gsscon.h>
43 #include <tr_apc.h>
44 #include <tr_rp.h>
45 #include <trust_router/tr_name.h>
46 #include <trp_internal.h>
47 #include <tr_gss.h>
48 #include <trp_ptable.h>
49 #include <trp_rtable.h>
50 #include <tr_debug.h>
51
52
53 static int trps_destructor(void *object)
54 {
55   TRPS_INSTANCE *trps=talloc_get_type_abort(object, TRPS_INSTANCE);
56   if (trps->rtable!=NULL)
57     trp_rtable_free(trps->rtable);
58   return 0;
59 }
60
61 TRPS_INSTANCE *trps_new (TALLOC_CTX *mem_ctx)
62 {
63   TRPS_INSTANCE *trps=talloc(mem_ctx, TRPS_INSTANCE);
64   if (trps!=NULL)  {
65     trps->hostname=NULL;
66     trps->port=0;
67     trps->cookie=NULL;
68     trps->conn=NULL;
69     trps->trpc=NULL;
70     trps->update_interval=(struct timeval){0,0};
71     trps->sweep_interval=(struct timeval){0,0};
72     trps->ptable=NULL;
73
74     trps->mq=tr_mq_new(trps);
75     if (trps->mq==NULL) {
76       /* failed to allocate mq */
77       talloc_free(trps);
78       return NULL;
79     }
80
81     trps->rtable=NULL;
82     if (trps_init_rtable(trps) != TRP_SUCCESS) {
83       /* failed to allocate rtable */
84       talloc_free(trps);
85       return NULL;
86     }
87
88     talloc_set_destructor((void *)trps, trps_destructor);
89   }
90   return trps;
91 }
92
93 /* create a new route table, first discarding an old one if necessary */
94 TRP_RC trps_init_rtable(TRPS_INSTANCE *trps)
95 {
96   if (trps->rtable != NULL) {
97     trp_rtable_free(trps->rtable);
98     trps->rtable=NULL;
99   }
100
101   trps->rtable=trp_rtable_new();
102   if (trps->rtable==NULL) {
103     return TRP_NOMEM;
104   }
105   return TRP_SUCCESS;
106 }
107
108 void trps_clear_rtable(TRPS_INSTANCE *trps)
109 {
110   trp_rtable_clear(trps->rtable);
111 }
112
113 void trps_free (TRPS_INSTANCE *trps)
114 {
115   if (trps!=NULL)
116     talloc_free(trps);
117 }
118
119 TR_MQ_MSG *trps_mq_pop(TRPS_INSTANCE *trps)
120 {
121   return tr_mq_pop(trps->mq);
122 }
123
124 void trps_mq_add(TRPS_INSTANCE *trps, TR_MQ_MSG *msg)
125 {
126   tr_mq_add(trps->mq, msg);
127 }
128
129 unsigned int trps_get_connect_interval(TRPS_INSTANCE *trps)
130 {
131   return trps->connect_interval.tv_sec;
132 }
133
134 void trps_set_connect_interval(TRPS_INSTANCE *trps, unsigned int interval)
135 {
136   trps->connect_interval.tv_sec=interval;
137   trps->connect_interval.tv_usec=0;
138 }
139
140 unsigned int trps_get_update_interval(TRPS_INSTANCE *trps)
141 {
142   return trps->update_interval.tv_sec;
143 }
144
145 void trps_set_update_interval(TRPS_INSTANCE *trps, unsigned int interval)
146 {
147   trps->update_interval.tv_sec=interval;
148   trps->update_interval.tv_usec=0;
149 }
150
151 unsigned int trps_get_sweep_interval(TRPS_INSTANCE *trps)
152 {
153   return trps->sweep_interval.tv_sec;
154 }
155
156 void trps_set_sweep_interval(TRPS_INSTANCE *trps, unsigned int interval)
157 {
158   trps->sweep_interval.tv_sec=interval;
159   trps->sweep_interval.tv_usec=0;
160 }
161
162 void trps_set_ctable(TRPS_INSTANCE *trps, TR_COMM_TABLE *comm)
163 {
164   if (trps->ctable!=NULL)
165     tr_comm_table_free(trps->ctable);
166   trps->ctable=comm;
167 }
168
169 void trps_set_ptable(TRPS_INSTANCE *trps, TRP_PTABLE *ptable)
170 {
171   if (trps->ptable!=NULL)
172     trp_ptable_free(trps->ptable);
173   trps->ptable=ptable;
174 }
175
176 void trps_set_peer_status_callback(TRPS_INSTANCE *trps, void (*cb)(TRP_PEER *, void *), void *cookie)
177 {
178   TRP_PTABLE_ITER *iter=NULL;
179   TRP_PEER *peer=NULL;
180   if (trps->ptable==NULL)
181     return;
182
183   iter=trp_ptable_iter_new(NULL);
184   for (peer=trp_ptable_iter_first(iter, trps->ptable); peer!=NULL; peer=trp_ptable_iter_next(iter))
185     trp_peer_set_conn_status_cb(peer, cb, cookie);
186   trp_ptable_iter_free(iter);
187 }
188
189 TRPC_INSTANCE *trps_find_trpc(TRPS_INSTANCE *trps, TRP_PEER *peer)
190 {
191   TRPC_INSTANCE *cur=NULL;
192   TR_NAME *name=NULL;
193   TR_NAME *peer_servicename=trp_peer_get_servicename(peer);
194
195   for (cur=trps->trpc; cur!=NULL; cur=trpc_get_next(cur)) {
196     name=trpc_get_gssname(cur);
197     if ((name!=NULL) && (0==tr_name_cmp(peer_servicename, name))) {
198       break;
199     }
200   }
201   return cur;
202 }
203
204 void trps_add_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *new)
205 {
206   if (trps->conn==NULL)
207     trps->conn=new;
208   else
209     trp_connection_append(trps->conn, new);
210
211   talloc_steal(trps, new);
212 }
213
214 /* ok to call more than once; guarantees connection no longer in the list.
215  * Caller is responsible for freeing the removed element afterwards.  */
216 void trps_remove_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *remove)
217 {
218   trps->conn=trp_connection_remove(trps->conn, remove);
219 }
220
221 void trps_add_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *trpc)
222 {
223   if (trps->trpc==NULL)
224     trps->trpc=trpc;
225   else
226     trpc_append(trps->trpc, trpc);
227
228   talloc_steal(trps, trpc);
229 }
230
231 /* ok to call more than once; guarantees trpc no longer in the list.
232  * Caller is responsible for freeing the removed element afterwards.  */
233 void trps_remove_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *remove)
234 {
235   trps->trpc=trpc_remove(trps->trpc, remove);
236 }
237
238 TRP_RC trps_send_msg(TRPS_INSTANCE *trps, TRP_PEER *peer, const char *msg)
239 {
240   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
241   TR_MQ_MSG *mq_msg=NULL;
242   char *msg_dup=NULL;
243   TRP_RC rc=TRP_ERROR;
244   TRPC_INSTANCE *trpc=NULL;
245
246   /* get the connection for this peer */
247   trpc=trps_find_trpc(trps, peer);
248   /* instead, let's let that happen and then clear the queue when an attempt to
249    * connect fails */
250   if (trpc==NULL) {
251     tr_warning("trps_send_msg: skipping message queued for missing TRP client entry.");
252   } else {
253     mq_msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_SEND, TR_MQ_PRIO_NORMAL);
254     msg_dup=talloc_strdup(mq_msg, msg); /* get local copy in mq_msg context */
255     tr_mq_msg_set_payload(mq_msg, msg_dup, NULL); /* no need for a free() func */
256     trpc_mq_add(trpc, mq_msg);
257     rc=TRP_SUCCESS;
258   }
259   talloc_free(tmp_ctx);
260   return rc;
261 }
262
263 static int trps_listen (TRPS_INSTANCE *trps, int port) 
264 {
265   int rc = 0;
266   int conn = -1;
267   int optval = 1;
268
269   union {
270     struct sockaddr_storage storage;
271     struct sockaddr_in in4;
272   } addr;
273
274   struct sockaddr_in *saddr = (struct sockaddr_in *) &addr.in4;
275
276   saddr->sin_port = htons (port);
277   saddr->sin_family = AF_INET;
278   saddr->sin_addr.s_addr = INADDR_ANY;
279
280   if (0 > (conn = socket (AF_INET, SOCK_STREAM, 0)))
281     return conn;
282
283   setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
284
285   if (0 > (rc = bind (conn, (struct sockaddr *) saddr, sizeof(struct sockaddr_in))))
286     return rc;
287
288   if (0 > (rc = listen(conn, 512)))
289     return rc;
290
291   tr_debug("trps_listen: TRP Server listening on port %d", port);
292   return conn;
293 }
294
295 /* get the currently selected route if available */
296 TRP_ROUTE *trps_get_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
297 {
298   return trp_rtable_get_entry(trps->rtable, comm, realm, peer);
299 }
300
301 TRP_ROUTE *trps_get_selected_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
302 {
303   tr_debug("trps_get_selected_route: entered. trps=%p, comm=%p, realm=%p", trps, comm, realm);
304   return trp_rtable_get_selected_entry(trps->rtable, comm, realm);
305 }
306
307 /* copy the result if you want to keep it */
308 TR_NAME *trps_get_next_hop(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
309 {
310   TRP_ROUTE *route=trps_get_selected_route(trps, comm, realm);
311   if (route==NULL)
312     return NULL;
313
314   return trp_route_get_next_hop(route);
315 }
316
317
318 /* mark a route as retracted */
319 static void trps_retract_route(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
320 {
321   trp_route_set_metric(entry, TRP_METRIC_INFINITY);
322   trp_route_set_triggered(entry, 1);
323 }
324
325 /* is this route retracted? */
326 static int trps_route_retracted(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
327 {
328   return (trp_metric_is_infinite(trp_route_get_metric(entry)));
329 }
330
331 static TRP_RC trps_read_message(TRPS_INSTANCE *trps, TRP_CONNECTION *conn, TR_MSG **msg)
332 {
333   int err=0;
334   char *buf=NULL;
335   size_t buflen = 0;
336   TRP_PEER *peer=NULL; /* entry in the peer table */
337   TR_NAME *conn_peer=NULL; /* name from the TRP_CONN, which comes from the gss context */
338
339   tr_debug("trps_read_message: started");
340   if (err = gsscon_read_encrypted_token(trp_connection_get_fd(conn),
341                                        *(trp_connection_get_gssctx(conn)), 
342                                        &buf,
343                                        &buflen)) {
344     tr_debug("trps_read_message: error");
345     if (buf)
346       free(buf);
347     return TRP_ERROR;
348   }
349
350   tr_debug("trps_read_message: message received, %u bytes.", (unsigned) buflen);
351   tr_debug("trps_read_message: %.*s", buflen, buf);
352
353   *msg=tr_msg_decode(buf, buflen);
354   free(buf);
355   if (*msg==NULL)
356     return TRP_NOPARSE;
357
358   conn_peer=trp_connection_get_peer(conn);
359   if (conn_peer==NULL) {
360     tr_err("trps_read_message: connection has no peer name");
361     return TRP_ERROR;
362   }
363
364   peer=trps_get_peer_by_gssname(trps, conn_peer);
365   if (peer==NULL) {
366     tr_err("trps_read_message: could not find peer with gssname=%s", trp_connection_get_gssname(conn));
367     return TRP_ERROR;
368   }
369
370   /* verify we received a message we support, otherwise drop it now */
371   switch (tr_msg_get_msg_type(*msg)) {
372   case TRP_UPDATE:
373     trp_upd_set_peer(tr_msg_get_trp_upd(*msg), tr_dup_name(conn_peer));
374     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 */
375     break;
376
377   case TRP_REQUEST:
378     trp_req_set_peer(tr_msg_get_trp_req(*msg), tr_dup_name(conn_peer));
379     break;
380
381   default:
382     tr_debug("trps_read_message: received unsupported message from %.*s", conn_peer->len, conn_peer->buf);
383     tr_msg_free_decoded(*msg);
384     *msg=NULL;
385     return TRP_UNSUPPORTED;
386   }
387   
388   return TRP_SUCCESS;
389 }
390
391 int trps_get_listener(TRPS_INSTANCE *trps,
392                       TRPS_MSG_FUNC msg_handler,
393                       TRP_AUTH_FUNC auth_handler,
394                       const char *hostname,
395                       unsigned int port,
396                       void *cookie)
397 {
398   int listen = -1;
399
400   if (0 > (listen = trps_listen(trps, port))) {
401     char errbuf[256];
402     if (0 == strerror_r(errno, errbuf, 256)) {
403       tr_debug("trps_get_listener: Error opening port %d: %s.", port, errbuf);
404     } else {
405       tr_debug("trps_get_listener: Unknown error openining port %d.", port);
406     }
407   } 
408
409   if (listen > 0) {
410     /* opening port succeeded */
411     tr_debug("trps_get_listener: Opened port %d.", port);
412     
413     /* make this socket non-blocking */
414     if (0 != fcntl(listen, F_SETFL, O_NONBLOCK)) {
415       tr_debug("trps_get_listener: Error setting O_NONBLOCK.");
416       close(listen);
417       listen=-1;
418     }
419   }
420
421   if (listen > 0) {
422     /* store the caller's request handler & cookie */
423     trps->msg_handler = msg_handler;
424     trps->auth_handler = auth_handler;
425     trps->hostname = talloc_strdup(trps, hostname);
426     trps->port = port;
427     trps->cookie = cookie;
428   }
429
430   return listen;
431 }
432
433 TRP_RC trps_authorize_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
434 {
435   /* try to establish a GSS context */
436   if (0!=trp_connection_auth(conn, trps->auth_handler, trps->cookie)) {
437     tr_notice("trps_authorize_connection: failed to authorize connection");
438     trp_connection_close(conn);
439     return TRP_ERROR;
440   }
441   tr_notice("trps_authorize_connection: authorized connection");
442   return TRP_SUCCESS;
443 }
444
445 void trps_handle_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
446 {
447   TR_MSG *msg=NULL;
448   TRP_RC rc=TRP_ERROR;
449
450   /* loop as long as the connection exists */
451   while (trp_connection_get_status(conn)==TRP_CONNECTION_UP) {
452     rc=trps_read_message(trps, conn, &msg);
453     switch(rc) {
454     case TRP_SUCCESS:
455       trps->msg_handler(trps, conn, msg); /* send the TR_MSG off to the callback */
456       break;
457
458     case TRP_ERROR:
459       trp_connection_close(conn);
460       break;
461
462     default:
463       tr_debug("trps_handle_connection: trps_read_message failed (%d)", rc);
464     }
465   }
466
467   tr_debug("trps_handle_connection: connection closed.");
468 }
469
470 /* TODO: check realm/comm, now part of the update instead of inforec */
471 static TRP_RC trps_validate_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
472 {
473   if (upd==NULL) {
474     tr_notice("trps_validate_update: null TRP update.");
475     return TRP_BADARG;
476   }
477
478   if (trp_upd_get_realm(upd)==NULL) {
479     tr_notice("trps_validate_update: received TRP update without realm.");
480     return TRP_ERROR;
481   }
482
483   if (trp_upd_get_comm(upd)==NULL) {
484     tr_notice("trps_validate_update: received TRP update without community.");
485     return TRP_ERROR;
486   }
487
488   if (trp_upd_get_inforec(upd)==NULL) {
489     tr_notice("trps_validate_update: received TRP update with no info records.");
490     return TRP_ERROR;
491   }
492
493   if (trp_upd_get_peer(upd)==NULL) {
494     tr_notice("trps_validate_update: received TRP update without origin peer information.");
495     return TRP_ERROR;
496   }
497
498   
499   return TRP_SUCCESS;
500 }
501
502 /* ensure that the update could be accepted if feasible */
503 static TRP_RC trps_validate_inforec(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
504 {
505   switch(trp_inforec_get_type(rec)) {
506   case TRP_INFOREC_TYPE_ROUTE:
507     if ((trp_inforec_get_trust_router(rec)==NULL)
508        || (trp_inforec_get_next_hop(rec)==NULL)) {
509       tr_debug("trps_validate_inforec: missing record info.");
510       return TRP_ERROR;
511     }
512
513     /* check for valid metric */
514     if (trp_metric_is_invalid(trp_inforec_get_metric(rec))) {
515       tr_debug("trps_validate_inforec: invalid metric (%u).", trp_inforec_get_metric(rec));
516       return TRP_ERROR;
517     }
518
519     /* check for valid interval */
520     if (trp_inforec_get_interval(rec)==TRP_INTERVAL_INVALID) {
521       tr_debug("trps_validate_inforec: invalid interval.");
522       return TRP_ERROR;
523     }
524     break;
525
526   case TRP_INFOREC_TYPE_COMMUNITY:
527     /* TODO: handle community updates -jlr*/
528     
529   default:
530     tr_notice("trps_validate_inforec: unsupported record type.");
531     return TRP_UNSUPPORTED;
532   }
533
534   return TRP_SUCCESS;
535 }
536
537 /* link cost to a peer */
538 static unsigned int trps_cost(TRPS_INSTANCE *trps, TR_NAME *peer)
539 {
540   return 1;
541 }
542
543 static unsigned int trps_advertised_metric(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
544 {
545   TRP_ROUTE *entry=trp_rtable_get_entry(trps->rtable, comm, realm, peer);
546   if (entry==NULL)
547     return TRP_METRIC_INFINITY;
548   return trp_route_get_metric(entry) + trps_cost(trps, peer);
549 }
550
551 static int trps_check_feasibility(TRPS_INSTANCE *trps, TR_NAME *realm, TR_NAME *comm, TRP_INFOREC *rec)
552 {
553   unsigned int rec_metric=trp_inforec_get_metric(rec);
554   unsigned int new_metric=0;
555   unsigned int current_metric=0;
556   TR_NAME *next_hop=NULL;
557
558   /* we check these in the validation stage, but just in case... */
559   if (trp_metric_is_invalid(rec_metric))
560     return 0;
561
562   /* retractions (aka infinite metrics) are always feasible */
563   if (trp_metric_is_infinite(rec_metric))
564     return 1;
565
566   /* updates from our current next hop are always feasible*/
567   next_hop=trps_get_next_hop(trps, comm, realm);
568   if ((next_hop!=NULL)
569      && (0==tr_name_cmp(next_hop,trp_inforec_get_next_hop(rec)))) {
570     return 1;
571   }
572     
573
574   /* compare the existing metric we advertise to what we would advertise
575    * if we accept this update */
576   current_metric=trps_advertised_metric(trps, comm, realm, trp_inforec_get_next_hop(rec));
577   new_metric=rec_metric + trps_cost(trps, trp_inforec_get_next_hop(rec));
578   if (new_metric <= current_metric)
579     return 1;
580   else
581     return 0;
582 }
583
584 /* uses memory pointed to by *ts, also returns that value. On error, its contents are {0,0} */
585 static struct timespec *trps_compute_expiry(TRPS_INSTANCE *trps, unsigned int interval, struct timespec *ts)
586 {
587   const unsigned int small_factor=3; /* how many intervals we wait before expiring */
588   if (0!=clock_gettime(CLOCK_REALTIME, ts)) {
589     tr_err("trps_compute_expiry: could not read realtime clock.");
590     ts->tv_sec=0;
591     ts->tv_nsec=0;
592   }
593   ts->tv_sec += small_factor*interval;
594   return ts;
595 }
596
597 static TRP_RC trps_accept_update(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
598 {
599   TRP_ROUTE *entry=NULL;
600
601   entry=trp_rtable_get_entry(trps->rtable,
602                              trp_upd_get_comm(upd),
603                              trp_upd_get_realm(upd),
604                              trp_inforec_get_next_hop(rec));
605   if (entry==NULL) {
606     entry=trp_route_new(NULL);
607     if (entry==NULL) {
608       tr_err("trps_accept_update: unable to allocate new entry.");
609       return TRP_NOMEM;
610     }
611
612     trp_route_set_comm(entry, trp_upd_dup_comm(upd));
613     trp_route_set_realm(entry, trp_upd_dup_realm(upd));
614     trp_route_set_peer(entry, trp_upd_dup_peer(upd));
615     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec));
616     trp_route_set_next_hop(entry, trp_inforec_dup_next_hop(rec));
617     /* TODO: pass next hop port (now defaults to TID_PORT) --jlr */
618     if ((trp_route_get_comm(entry)==NULL)
619        ||(trp_route_get_realm(entry)==NULL)
620        ||(trp_route_get_peer(entry)==NULL)
621        ||(trp_route_get_trust_router(entry)==NULL)
622        ||(trp_route_get_next_hop(entry)==NULL)) {
623       /* at least one field could not be allocated */
624       tr_err("trps_accept_update: unable to allocate all fields for entry.");
625       trp_route_free(entry);
626       return TRP_NOMEM;
627     }
628     trp_rtable_add(trps->rtable, entry);
629   }
630
631   /* We now have an entry in the table, whether it's new or not. Update metric and expiry, unless
632    * the metric is infinity. An infinite metric can only occur here if we just retracted an existing
633    * route (we never accept retractions as new routes), so there is no risk of leaving the expiry
634    * time unset on a new route entry. */
635   tr_debug("trps_accept_update: accepting route update.");
636   trp_route_set_metric(entry, trp_inforec_get_metric(rec));
637   trp_route_set_interval(entry, trp_inforec_get_interval(rec));
638
639   /* check whether the trust router has changed */
640   if (0!=tr_name_cmp(trp_route_get_trust_router(entry),
641                      trp_inforec_get_trust_router(rec))) {
642     /* The name changed. Set this route as triggered. */
643     tr_debug("trps_accept_update: trust router for route changed.");
644     trp_route_set_triggered(entry, 1);
645     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec)); /* frees old name */
646   }
647   if (!trps_route_retracted(trps, entry)) {
648     tr_debug("trps_accept_update: route not retracted, setting expiry timer.");
649     trp_route_set_expiry(entry, trps_compute_expiry(trps,
650                                                      trp_route_get_interval(entry),
651                                                      trp_route_get_expiry(entry)));
652   }
653   return TRP_SUCCESS;
654 }
655
656 static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
657 {
658   unsigned int feas=0;
659   TRP_INFOREC *rec=NULL;
660   TRP_ROUTE *route=NULL;
661
662   if (trps_validate_update(trps, upd) != TRP_SUCCESS) {
663     tr_notice("trps_handle_update: received invalid TRP update.");
664     return TRP_ERROR;
665   }
666
667   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
668     /* validate/sanity check the record update */
669     if (trps_validate_inforec(trps, rec) != TRP_SUCCESS) {
670       tr_notice("trps_handle_update: invalid record in TRP update, discarding entire update.");
671       return TRP_ERROR;
672     }
673   }
674
675   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
676     /* determine feasibility */
677     feas=trps_check_feasibility(trps, trp_upd_get_realm(upd), trp_upd_get_comm(upd), rec);
678     tr_debug("trps_handle_update: record feasibility=%d", feas);
679
680     /* do we have an existing route? */
681     route=trps_get_route(trps,
682                          trp_upd_get_comm(upd),
683                          trp_upd_get_realm(upd),
684                          trp_upd_get_peer(upd));
685     if (route!=NULL) {
686       /* there was a route table entry already */
687       tr_debug("trps_handle_updates: route entry already exists.");
688       if (feas) {
689         /* Update is feasible. Accept it. */
690         trps_accept_update(trps, upd, rec);
691       } else {
692         /* Update is infeasible. Ignore it unless the trust router has changed. */
693         if (0!=tr_name_cmp(trp_route_get_trust_router(route),
694                            trp_inforec_get_trust_router(rec))) {
695           /* the trust router associated with the route has changed, treat update as a retraction */
696           trps_retract_route(trps, route);
697         }
698       }
699     } else {
700       /* No existing route table entry. Ignore it unless it is feasible and not a retraction. */
701       tr_debug("trps_handle_update: no route entry exists yet.");
702       if (feas && trp_metric_is_finite(trp_inforec_get_metric(rec)))
703         trps_accept_update(trps, upd, rec);
704     }
705   }
706   return TRP_SUCCESS;
707 }
708
709 static TRP_RC trps_validate_request(TRPS_INSTANCE *trps, TRP_REQ *req)
710 {
711   if (req==NULL) {
712     tr_notice("trps_validate_request: null TRP request.");
713     return TRP_BADARG;
714   }
715
716   if (trp_req_get_comm(req)==NULL) {
717     tr_notice("trps_validate_request: received TRP request with null community.");
718     return TRP_ERROR;
719   }
720   
721   if (trp_req_get_realm(req)==NULL) {
722     tr_notice("trps_validate_request: received TRP request with null realm.");
723     return TRP_ERROR;
724   }
725   
726   if (trp_req_get_peer(req)==NULL) {
727     tr_notice("trps_validate_request: received TRP request without origin peer information.");
728     return TRP_ERROR;
729   }
730   
731   return TRP_SUCCESS;
732 }
733
734 /* choose the best route to comm/realm, optionally excluding routes to a particular peer */
735 static TRP_ROUTE *trps_find_best_route(TRPS_INSTANCE *trps,
736                                         TR_NAME *comm,
737                                         TR_NAME *realm,
738                                         TR_NAME *exclude_peer)
739 {
740   TRP_ROUTE **entry=NULL;
741   TRP_ROUTE *best=NULL;
742   size_t n_entry=0;
743   unsigned int kk=0;
744   unsigned int kk_min=0;
745   unsigned int min_metric=TRP_METRIC_INFINITY;
746
747   entry=trp_rtable_get_realm_entries(trps->rtable, comm, realm, &n_entry);
748   for (kk=0; kk<n_entry; kk++) {
749     if (trp_route_get_metric(entry[kk]) < min_metric) {
750       if ((exclude_peer==NULL) || (0!=tr_name_cmp(trp_route_get_peer(entry[kk]),
751                                                   exclude_peer))) {
752         kk_min=kk;
753         min_metric=trp_route_get_metric(entry[kk]);
754       } 
755     }
756   }
757   if (trp_metric_is_finite(min_metric))
758     best=entry[kk_min];
759   
760   talloc_free(entry);
761   return best;
762 }
763
764 /* TODO: think this through more carefully. At least ought to add hysteresis
765  * to avoid flapping between routers or routes. */
766 TRP_RC trps_update_active_routes(TRPS_INSTANCE *trps)
767 {
768   size_t n_comm=0, ii=0;
769   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
770   size_t n_realm=0, jj=0;
771   TR_NAME **realm=NULL;
772   TRP_ROUTE *best_route=NULL, *cur_route=NULL;
773   unsigned int best_metric=0, cur_metric=0;
774
775   for (ii=0; ii<n_comm; ii++) {
776     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
777     for (jj=0; jj<n_realm; jj++) {
778       best_route=trps_find_best_route(trps, comm[ii], realm[jj], NULL);
779       if (best_route==NULL)
780         best_metric=TRP_METRIC_INFINITY;
781       else
782         best_metric=trp_route_get_metric(best_route);
783
784       cur_route=trps_get_selected_route(trps, comm[ii], realm[jj]);
785       if (cur_route!=NULL) {
786         cur_metric=trp_route_get_metric(cur_route);
787         if ((best_metric < cur_metric) && (trp_metric_is_finite(best_metric))) {
788           /* The new route has a lower metric than the previous, and is finite. Accept. */
789           trp_route_set_selected(cur_route, 0);
790           trp_route_set_selected(best_route, 1);
791         } else if (!trp_metric_is_finite(cur_metric)) /* rejects infinite or invalid metrics */
792           trp_route_set_selected(cur_route, 0);
793       } else if (trp_metric_is_finite(best_metric)) {
794         trp_route_set_selected(best_route, 1);
795       }
796     }
797     if (realm!=NULL)
798       talloc_free(realm);
799     realm=NULL; n_realm=0;
800   }
801   if (comm!=NULL)
802     talloc_free(comm);
803   comm=NULL; n_comm=0;
804
805   return TRP_SUCCESS;
806 }
807
808 /* true if curtime >= expiry */
809 static int trps_expired(struct timespec *expiry, struct timespec *curtime)
810 {
811   return ((curtime->tv_sec > expiry->tv_sec)
812          || ((curtime->tv_sec == expiry->tv_sec)
813             &&(curtime->tv_nsec >= expiry->tv_nsec)));
814 }
815
816 /* Sweep for expired routes. For each expired route, if its metric is infinite, the route is flushed.
817  * If its metric is finite, the metric is set to infinite and the route's expiration time is updated. */
818 TRP_RC trps_sweep_routes(TRPS_INSTANCE *trps)
819 {
820   struct timespec sweep_time={0,0};
821   TRP_ROUTE **entry=NULL;
822   size_t n_entry=0;
823   size_t ii=0;
824
825   /* use a single time for the entire sweep */
826   if (0!=clock_gettime(CLOCK_REALTIME, &sweep_time)) {
827     tr_err("trps_sweep_routes: could not read realtime clock.");
828     sweep_time.tv_sec=0;
829     sweep_time.tv_nsec=0;
830     return TRP_ERROR;
831   }
832
833   entry=trp_rtable_get_entries(trps->rtable, &n_entry); /* must talloc_free *entry */
834
835   /* loop over the entries */
836   for (ii=0; ii<n_entry; ii++) {
837     if (!trp_route_is_local(entry[ii]) && trps_expired(trp_route_get_expiry(entry[ii]), &sweep_time)) {
838       tr_debug("trps_sweep_routes: route expired.");
839       if (!trp_metric_is_finite(trp_route_get_metric(entry[ii]))) {
840         /* flush route */
841         tr_debug("trps_sweep_routes: metric was infinity, flushing route.");
842         trp_rtable_remove(trps->rtable, entry[ii]); /* entry[ii] is no longer valid */
843         entry[ii]=NULL;
844       } else {
845         /* set metric to infinity and reset timer */
846         tr_debug("trps_sweep_routes: setting metric to infinity and resetting expiry.");
847         trp_route_set_metric(entry[ii], TRP_METRIC_INFINITY);
848         trp_route_set_expiry(entry[ii], trps_compute_expiry(trps,
849                                                              trp_route_get_interval(entry[ii]),
850                                                              trp_route_get_expiry(entry[ii])));
851       }
852     }
853   }
854
855   talloc_free(entry);
856   return TRP_SUCCESS;
857 }
858
859 /* add metrics */
860 static unsigned int trps_metric_add(unsigned int m1, unsigned int m2)
861 {
862   if (trp_metric_is_invalid(m1) || trp_metric_is_invalid(m2))
863     return TRP_METRIC_INVALID;
864
865   if (trp_metric_is_infinite(m1) || trp_metric_is_infinite(m2))
866     return TRP_METRIC_INFINITY;
867
868   if (trp_metric_is_finite(m1+m2))
869     return m1+m2;
870   else
871     return TRP_METRIC_INFINITY;
872 }
873
874 /* convert an rentry into a new trp update info record */
875 static TRP_INFOREC *trps_route_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
876 {
877   TRP_INFOREC *rec=trp_inforec_new(mem_ctx, TRP_INFOREC_TYPE_ROUTE);
878   unsigned int linkcost=0;
879
880   if (rec!=NULL) {
881     if (trp_route_is_local(route))
882       linkcost=0;
883     else {
884       linkcost=trp_peer_get_linkcost(trps_get_peer_by_gssname(trps,
885                                                               trp_route_get_peer(route)));
886     }
887
888     /* Note that we leave the next hop empty since the recipient fills that in.
889      * This is where we add the link cost (currently always 1) to the next peer. */
890     if ((trp_inforec_set_trust_router(rec, trp_route_dup_trust_router(route)) != TRP_SUCCESS)
891        ||(trp_inforec_set_metric(rec,
892                                  trps_metric_add(trp_route_get_metric(route),
893                                                  linkcost)) != TRP_SUCCESS)
894        ||(trp_inforec_set_interval(rec, trps_get_update_interval(trps)) != TRP_SUCCESS)) {
895       tr_err("trps_route_to_inforec: error creating route update.");
896       talloc_free(rec);
897       rec=NULL;
898     }
899   }
900   return rec;
901 }
902
903 static TRP_UPD *trps_route_to_upd(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
904 {
905   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
906   TRP_UPD *upd=trp_upd_new(tmp_ctx);
907   TRP_INFOREC *rec=NULL;
908
909   if (upd==NULL) {
910     tr_err("trps_route_to_upd: could not create update message.");
911     goto cleanup;
912   }
913   trp_upd_set_realm(upd, trp_route_dup_realm(route));
914   if (trp_upd_get_realm(upd)==NULL) {
915     tr_err("trps_route_to_upd: could not copy realm.");
916     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
917     goto cleanup;
918   }
919   trp_upd_set_comm(upd, trp_route_dup_comm(route));
920   if (trp_upd_get_comm(upd)==NULL) {
921     tr_err("trps_route_to_upd: could not copy comm.");
922     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
923     goto cleanup;
924   }
925   rec=trps_route_to_inforec(tmp_ctx, trps, route);
926   if (rec==NULL) {
927     tr_err("trps_route_to_upd: could not create route info record for realm %.*s in comm %.*s.",
928            trp_route_get_realm(route)->len, trp_route_get_realm(route)->buf,
929            trp_route_get_comm(route)->len, trp_route_get_comm(route)->buf);
930     upd=NULL; /* it's till in tmp_ctx, so it will be freed */
931     goto cleanup;
932   }
933   trp_upd_add_inforec(upd, rec);
934
935   /* sucess */
936   talloc_steal(mem_ctx, upd);
937
938 cleanup:
939   talloc_free(tmp_ctx);
940   return upd;
941 }
942
943 /* select the correct route to comm/realm to be announced to peer */
944 static TRP_ROUTE *trps_select_realm_update(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer_gssname)
945 {
946   TRP_ROUTE *route;
947
948   /* Take the currently selected route unless it is through the peer we're sending the update to.
949    * I.e., enforce the split horizon rule. */
950   route=trp_rtable_get_selected_entry(trps->rtable, comm, realm);
951   if (route==NULL) {
952     /* No selected route, this should only happen if the only route has been retracted,
953      * in which case we do not want to advertise it. */
954     return NULL;
955   }
956   tr_debug("trps_select_realm_update: %s vs %s", peer_gssname->buf,
957            trp_route_get_peer(route)->buf);
958   if (0==tr_name_cmp(peer_gssname, trp_route_get_peer(route))) {
959     tr_debug("trps_select_realm_update: matched, finding alternate route");
960     /* the selected entry goes through the peer we're reporting to, choose an alternate */
961     route=trps_find_best_route(trps, comm, realm, peer_gssname);
962     if ((route==NULL) || (!trp_metric_is_finite(trp_route_get_metric(route))))
963       return NULL; /* don't advertise a nonexistent or retracted route */
964   }
965   return route;
966 }
967
968 /* Add TRP_UPD msgs to the updates GPtrArray. Caller needs to arrange for these to be freed. */
969 static TRP_RC trps_select_route_updates_for_peer(TALLOC_CTX *mem_ctx,
970                                                  GPtrArray *updates,
971                                                  TRPS_INSTANCE *trps,
972                                                  TR_NAME *peer_gssname,
973                                                  int triggered)
974 {
975   size_t n_comm=0;
976   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
977   TR_NAME **realm=NULL;
978   size_t n_realm=0;
979   size_t ii=0, jj=0;
980   TRP_ROUTE *best=NULL;
981   TRP_UPD *upd=NULL;
982
983   if (updates==NULL)
984     return TRP_BADARG;
985
986   for (ii=0; ii<n_comm; ii++) {
987     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
988     for (jj=0; jj<n_realm; jj++) {
989       best=trps_select_realm_update(trps, comm[ii], realm[jj], peer_gssname);
990       /* If we found a route, add it to the list. If triggered!=0, then only
991        * add triggered routes. */
992       if ((best!=NULL) && ((!triggered) || trp_route_is_triggered(best))) {
993         upd=trps_route_to_upd(mem_ctx, trps, best);
994         if (upd==NULL) {
995           tr_err("trps_select_route_updates_for_peer: unable to create update message.");
996           continue;
997         }
998         g_ptr_array_add(updates, upd);
999       }
1000     }
1001     
1002     if (realm!=NULL)
1003       talloc_free(realm);
1004     realm=NULL;
1005     n_realm=0;
1006   }
1007
1008   if (comm!=NULL)
1009     talloc_free(comm);
1010   
1011   return TRP_SUCCESS;
1012 }
1013
1014 static TRP_INFOREC *trps_memb_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_COMM_MEMB *memb)
1015 {
1016   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1017   TRP_INFOREC *rec=NULL;
1018   TR_COMM *comm=NULL;
1019
1020   if (memb==NULL)
1021     goto cleanup;
1022
1023   comm=tr_comm_memb_get_comm(memb);
1024   rec=trp_inforec_new(tmp_ctx, TRP_INFOREC_TYPE_COMMUNITY);
1025   if (rec==NULL)
1026     goto cleanup;
1027   
1028   if (TRP_SUCCESS!=trp_inforec_set_comm_type(rec, tr_comm_get_type(comm))) {
1029     rec=NULL;
1030     goto cleanup;
1031   }
1032   
1033   if (TRP_SUCCESS!=trp_inforec_set_role(rec, tr_comm_memb_get_role(memb))) {
1034     rec=NULL;
1035     goto cleanup;
1036   }
1037
1038   if ((NULL!=tr_comm_get_apcs(comm)) &&
1039       ( (TRP_SUCCESS!=trp_inforec_set_apcs(rec,
1040                                            tr_apc_dup(rec, tr_comm_get_apcs(comm)))) ||
1041         (NULL==trp_inforec_get_apcs(rec)))) {
1042     rec=NULL;
1043     goto cleanup;
1044   }
1045
1046   if ((NULL!=tr_comm_get_owner_realm(comm)) &&
1047       ( (TRP_SUCCESS!=trp_inforec_set_owner_realm(rec, tr_dup_name(tr_comm_get_owner_realm(comm)))) ||
1048         (NULL==trp_inforec_get_owner_realm(rec)))) {
1049     rec=NULL;
1050     goto cleanup;
1051   }
1052
1053   if ((NULL!=tr_comm_get_owner_contact(comm)) &&
1054       ( (TRP_SUCCESS!=trp_inforec_set_owner_contact(rec, tr_dup_name(tr_comm_get_owner_contact(comm)))) ||
1055         (NULL==trp_inforec_get_owner_contact(rec)))) {
1056     rec=NULL;
1057     goto cleanup;
1058   }
1059
1060   if ((NULL!=tr_comm_memb_get_provenance(memb)) &&
1061       (TRP_SUCCESS!=trp_inforec_set_provenance(rec, tr_comm_memb_get_provenance(memb)))) {
1062     rec=NULL;
1063     goto cleanup;
1064   }
1065
1066   if (TRP_SUCCESS!=trp_inforec_set_interval(rec, tr_comm_memb_get_interval(memb))) {
1067     rec=NULL;
1068     goto cleanup;
1069   }
1070
1071   /* success! */
1072   talloc_steal(mem_ctx, rec);
1073
1074 cleanup:
1075   talloc_free(tmp_ctx);
1076   return rec;
1077 }
1078
1079 /* construct an update with all the inforecs for comm/realm/role to be sent to peer */
1080 static TRP_UPD *trps_comm_update(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_NAME *peer_gssname, TR_COMM *comm, TR_REALM *realm)
1081 {
1082   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1083   TRP_UPD *upd=trp_upd_new(tmp_ctx);
1084   TRP_INFOREC *rec=NULL;
1085   TR_COMM_ITER *iter=NULL;
1086   TR_COMM_MEMB *memb=NULL;
1087
1088   if (upd==NULL)
1089     goto cleanup;
1090   
1091   trp_upd_set_comm(upd, tr_comm_dup_id(comm));
1092   trp_upd_set_realm(upd, tr_realm_dup_id(realm));
1093   /* leave peer empty */
1094
1095   iter=tr_comm_iter_new(tmp_ctx);
1096   if (iter==NULL) {
1097     tr_err("trps_comm_update: unable to allocate iterator.");
1098     upd=NULL;
1099     goto cleanup;
1100   }
1101   
1102   /* now add inforecs */
1103   switch (realm->role) {
1104   case TR_ROLE_IDP:
1105     memb=tr_comm_table_find_idp_memb(trps->ctable,
1106                                      tr_realm_get_id(realm),
1107                                      tr_comm_get_id(comm));
1108     break;
1109   case TR_ROLE_RP:
1110     memb=tr_comm_table_find_rp_memb(trps->ctable,
1111                                     tr_realm_get_id(realm),
1112                                     tr_comm_get_id(comm));
1113     break;
1114   default:
1115     break;
1116   }
1117   if (memb!=NULL) {
1118     for (memb=tr_comm_memb_iter_first(iter, memb);
1119          memb!=NULL;
1120          memb=tr_comm_memb_iter_next(iter)) {
1121       rec=trps_memb_to_inforec(tmp_ctx, trps, memb);
1122       if (rec==NULL) {
1123         tr_err("trps_comm_update: unable to allocate inforec.");
1124         upd=NULL;
1125         goto cleanup;
1126       }
1127       trp_upd_add_inforec(upd, rec);
1128     }
1129   }
1130
1131   if (trp_upd_get_inforec(upd)==NULL)
1132     upd=NULL; /* no inforecs, no reason to send the update */
1133   else
1134     talloc_steal(mem_ctx, upd); /* success! */
1135
1136 cleanup:
1137   talloc_free(tmp_ctx);
1138   return upd;
1139 }
1140
1141 /* Find all community updates to send to a peer and add these as TR_UPD records
1142  * to the updates GPtrArray. */
1143 static TRP_RC trps_select_comm_updates_for_peer(TALLOC_CTX *mem_ctx, GPtrArray *updates, TRPS_INSTANCE *trps, TR_NAME *peer_gssname)
1144 {
1145   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1146   TR_COMM_ITER *comm_iter=NULL;
1147   TR_COMM *comm=NULL;
1148   TR_COMM_ITER *realm_iter=NULL;
1149   TR_REALM *realm=NULL;
1150   TRP_UPD *upd=NULL;
1151   TRP_RC rc=TRP_ERROR;
1152   
1153   comm_iter=tr_comm_iter_new(tmp_ctx);
1154   realm_iter=tr_comm_iter_new(tmp_ctx);
1155   if ((comm_iter==NULL) || (realm_iter==NULL)) {
1156     tr_err("trps_select_comm_updates_for_peer: unable to allocate iterator.");
1157     rc=TRP_NOMEM;
1158     goto cleanup;
1159   }
1160
1161   /* do every community */
1162   for (comm=tr_comm_table_iter_first(comm_iter, trps->ctable);
1163        comm!=NULL;
1164        comm=tr_comm_table_iter_next(comm_iter)) {
1165     /* do every realm in this community */
1166     tr_debug("trps_select_comm_updates_for_peer: looking through community %.*s",
1167              tr_comm_get_id(comm)->len,
1168              tr_comm_get_id(comm)->buf);
1169     for (realm=tr_realm_iter_first(realm_iter, trps->ctable, tr_comm_get_id(comm));
1170          realm!=NULL;
1171          realm=tr_realm_iter_next(realm_iter)) {
1172       /* get the update for this comm/realm */
1173       tr_debug("trps_select_comm_updates_for_peer: adding realm %.*s",
1174                tr_realm_get_id(realm)->len,
1175                tr_realm_get_id(realm)->buf);
1176       upd=trps_comm_update(mem_ctx, trps, peer_gssname, comm, realm);
1177       if (upd!=NULL)
1178         g_ptr_array_add(updates, upd);
1179     }
1180   }
1181
1182 cleanup:
1183   talloc_free(tmp_ctx);
1184   return rc;
1185 }
1186
1187
1188 /* helper for trps_update_one_peer. Frees the TRP_UPD pointed to by a GPtrArray element */
1189 static void trps_trp_upd_destroy(gpointer data)
1190 {
1191   trp_upd_free((TRP_UPD *)data);
1192 }
1193
1194 /* all routes/communities to a single peer, unless comm/realm are specified (both or neither must be NULL) */
1195 static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
1196                                    TRP_PEER *peer,
1197                                    TRP_UPDATE_TYPE update_type,
1198                                    TR_NAME *comm,
1199                                    TR_NAME *realm)
1200 {
1201   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1202   TR_MSG msg; /* not a pointer! */
1203   TRP_UPD *upd=NULL;
1204   TRP_ROUTE *route=NULL;
1205   size_t ii=0;
1206   char *encoded=NULL;
1207   TRP_RC rc=TRP_ERROR;
1208   TR_NAME *peer_label=trp_peer_get_label(peer);
1209   GPtrArray *updates=g_ptr_array_new_with_free_func(trps_trp_upd_destroy);
1210
1211   if (updates==NULL) {
1212     tr_err("trps_update_one_peer: unable to allocate updates array.");
1213     rc=TRP_NOMEM;
1214     goto cleanup;
1215   }
1216
1217   switch (update_type) {
1218   case TRP_UPDATE_TRIGGERED:
1219     tr_debug("trps_update_one_peer: preparing triggered update for %.*s",
1220              peer_label->len, peer_label->buf);
1221     break;
1222   case TRP_UPDATE_SCHEDULED:
1223     tr_debug("trps_update_one_peer: preparing scheduled update for %.*s",
1224              peer_label->len, peer_label->buf);
1225     break;
1226   case TRP_UPDATE_REQUESTED:
1227     tr_debug("trps_update_one_peer: preparing requested update for %.*s",
1228              peer_label->len, peer_label->buf);
1229     break;
1230   default:
1231     tr_err("trps_update_one_peer: invalid update type requested.");
1232     rc=TRP_BADARG;
1233     goto cleanup;
1234   }
1235
1236   /* First, gather route updates. */
1237   tr_debug("trps_update_one_peer: selecting route updates for %.*s.", peer_label->len, peer_label->buf);
1238   if ((comm==NULL) && (realm==NULL)) {
1239     /* do all realms */
1240     rc=trps_select_route_updates_for_peer(tmp_ctx,
1241                                           updates,
1242                                           trps,
1243                                           peer_label,
1244                                           update_type==TRP_UPDATE_TRIGGERED);
1245   } else if ((comm!=NULL) && (realm!=NULL)) {
1246     /* a single community/realm was requested */
1247     route=trps_select_realm_update(trps, comm, realm, peer_label);
1248     if (route==NULL) {
1249       /* we have no actual update to send back, MUST send a retraction */
1250       tr_debug("trps_update_one_peer: community/realm without route requested, sending mandatory retraction.");
1251       route=trp_route_new(tmp_ctx);
1252       trp_route_set_comm(route, tr_dup_name(comm));
1253       trp_route_set_realm(route, tr_dup_name(realm));
1254       trp_route_set_peer(route, tr_new_name(""));
1255       trp_route_set_metric(route, TRP_METRIC_INFINITY);
1256       trp_route_set_trust_router(route, tr_new_name(""));
1257       trp_route_set_next_hop(route, tr_new_name(""));
1258     }
1259     upd=trps_route_to_upd(tmp_ctx, trps, route);
1260     if (upd==NULL) {
1261       tr_err("trps_update_one_peer: unable to allocate route update.");
1262       rc=TRP_NOMEM;
1263       goto cleanup;
1264     }
1265     g_ptr_array_add(updates, upd);
1266   } else {
1267     tr_err("trps_update_one_peer: error: only comm or realm was specified. Need both or neither.");
1268     rc=TRP_ERROR;
1269     goto cleanup;
1270   }
1271
1272   /* Second, gather community updates */
1273   tr_debug("trps_update_one_peer: selecting community updates for %.*s.", peer_label->len, peer_label->buf);
1274   rc=trps_select_comm_updates_for_peer(tmp_ctx, updates, trps, peer_label);
1275
1276   /* see if we have anything to send */
1277   if (updates->len<=0)
1278     tr_debug("trps_update_one_peer: no updates for %.*s", peer_label->len, peer_label->buf);
1279   else {
1280     tr_debug("trps_update_one_peer: sending %d update messages.", updates->len);
1281     for (ii=0; ii<updates->len; ii++) {
1282       upd=(TRP_UPD *)g_ptr_array_index(updates, ii);
1283       /* now encode the update message */
1284       tr_msg_set_trp_upd(&msg, upd);
1285       encoded=tr_msg_encode(&msg);
1286       if (encoded==NULL) {
1287         tr_err("trps_update_one_peer: error encoding update.");
1288         rc=TRP_ERROR;
1289         goto cleanup;
1290       }
1291
1292       tr_debug("trps_update_one_peer: adding message to queue.");
1293       if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
1294         tr_err("trps_update_one_peer: error queueing update.");
1295       else
1296         tr_debug("trps_update_one_peer: update queued successfully.");
1297
1298       tr_msg_free_encoded(encoded);
1299       encoded=NULL;
1300     }
1301   }
1302
1303   rc=TRP_SUCCESS;
1304
1305 cleanup:
1306   if (updates!=NULL)
1307     g_ptr_array_free(updates, TRUE); /* frees any TRP_UPD records */
1308   talloc_free(tmp_ctx);
1309   return rc;
1310 }
1311
1312 /* all routes/communities to all peers */
1313 TRP_RC trps_update(TRPS_INSTANCE *trps, TRP_UPDATE_TYPE update_type)
1314 {
1315   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1316   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
1317   TRP_PEER *peer=NULL;
1318   TRP_RC rc=TRP_SUCCESS;
1319
1320   if (trps->ptable==NULL)
1321     return TRP_SUCCESS; /* no peers, nothing to do */
1322
1323   if (iter==NULL) {
1324     tr_err("trps_update: failed to allocate peer table iterator.");
1325     talloc_free(tmp_ctx);
1326     return TRP_NOMEM;
1327   }
1328
1329   for (peer=trp_ptable_iter_first(iter, trps->ptable);
1330        peer!=NULL && rc==TRP_SUCCESS;
1331        peer=trp_ptable_iter_next(iter))
1332   {
1333     if (!trps_peer_connected(trps, peer)) {
1334       TR_NAME *peer_label=trp_peer_get_label(peer);
1335       tr_debug("trps_update: no TRP connection to %.*s, skipping.",
1336                peer_label->len, peer_label->buf);
1337       continue;
1338     }
1339     rc=trps_update_one_peer(trps, peer, update_type, NULL, NULL);
1340   }
1341
1342   tr_debug("trps_update: rc=%u after attempting update.", rc);
1343   trp_ptable_iter_free(iter);
1344   trp_rtable_clear_triggered(trps->rtable); /* don't re-send triggered updates */
1345   talloc_free(tmp_ctx);
1346   return rc;
1347 }        
1348
1349 TRP_RC trps_add_route(TRPS_INSTANCE *trps, TRP_ROUTE *route)
1350 {
1351   trp_rtable_add(trps->rtable, route); /* should return status */
1352   return TRP_SUCCESS; 
1353 }
1354
1355 /* steals the peer object */
1356 TRP_RC trps_add_peer(TRPS_INSTANCE *trps, TRP_PEER *peer)
1357 {
1358   if (trps->ptable==NULL) {
1359     trps->ptable=trp_ptable_new(trps);
1360     if (trps->ptable==NULL)
1361       return TRP_NOMEM;
1362   }
1363   return trp_ptable_add(trps->ptable, peer);
1364 }
1365
1366 TRP_PEER *trps_get_peer_by_gssname(TRPS_INSTANCE *trps, TR_NAME *gssname)
1367 {
1368   if (trps->ptable==NULL)
1369     return NULL;
1370
1371   return trp_ptable_find_gss_name(trps->ptable, gssname);
1372 }
1373
1374 TRP_PEER *trps_get_peer_by_servicename(TRPS_INSTANCE *trps, TR_NAME *servicename)
1375 {
1376   if (trps->ptable==NULL)
1377     return NULL;
1378
1379   return trp_ptable_find_servicename(trps->ptable, servicename);
1380 }
1381
1382 int trps_peer_connected(TRPS_INSTANCE *trps, TRP_PEER *peer)
1383 {
1384   TRPC_INSTANCE *trpc=trps_find_trpc(trps, peer);
1385   if (trpc==NULL)
1386     return 0;
1387
1388   if (trpc_get_status(trpc)==TRP_CONNECTION_UP)
1389     return 1;
1390   else
1391     return 0;
1392 }
1393
1394
1395 static TRP_RC trps_handle_request(TRPS_INSTANCE *trps, TRP_REQ *req)
1396 {
1397   TR_NAME *comm=NULL;
1398   TR_NAME *realm=NULL;
1399
1400   tr_debug("trps_handle_request: handling TRP request.");
1401
1402   if (trps_validate_request(trps, req) != TRP_SUCCESS) {
1403     tr_notice("trps_handle_request: received invalid TRP request.");
1404     return TRP_ERROR;
1405   }
1406
1407   if (!trp_req_is_wildcard(req)) {
1408     comm=trp_req_get_comm(req);
1409     realm=trp_req_get_realm(req);
1410     tr_debug("trps_handle_request: route for %.*s/%.*s requested.",
1411              comm->len, comm->buf, realm->len, realm->buf);
1412   } else {
1413     tr_debug("trps_handle_request: all routes requested.");
1414     /* leave comm/realm NULL */
1415   }
1416   return trps_update_one_peer(trps,
1417                               trps_get_peer_by_gssname(trps, trp_req_get_peer(req)),
1418                               TRP_UPDATE_REQUESTED,
1419                               comm,
1420                               realm);
1421 }
1422
1423
1424 TRP_RC trps_handle_tr_msg(TRPS_INSTANCE *trps, TR_MSG *tr_msg)
1425 {
1426   TRP_RC rc=TRP_ERROR;
1427
1428   switch (tr_msg_get_msg_type(tr_msg)) {
1429   case TRP_UPDATE:
1430     rc=trps_handle_update(trps, tr_msg_get_trp_upd(tr_msg));
1431     if (rc==TRP_SUCCESS) {
1432       rc=trps_update_active_routes(trps);
1433       trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
1434     }
1435     return rc;
1436
1437   case TRP_REQUEST:
1438     rc=trps_handle_request(trps, tr_msg_get_trp_req(tr_msg));
1439     return rc;
1440
1441   default:
1442     /* unknown error or one we don't care about (e.g., TID messages) */
1443     return TRP_ERROR;
1444   }
1445 }
1446
1447 /* send wildcard route request to a peer */
1448 TRP_RC trps_wildcard_route_req(TRPS_INSTANCE *trps, TR_NAME *peer_servicename)
1449 {
1450   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1451   TRP_PEER *peer=trps_get_peer_by_servicename(trps, peer_servicename);
1452   TR_MSG msg; /* not a pointer */
1453   TRP_REQ *req=trp_req_new(tmp_ctx);
1454   char *encoded=NULL;
1455   TRP_RC rc=TRP_ERROR;
1456
1457   if (peer==NULL) {
1458     tr_err("trps_wildcard_route_req: unknown peer (%.*s).", peer_servicename->len, peer_servicename->buf);
1459     rc=TRP_BADARG;
1460     goto cleanup;
1461   }
1462   if ((req==NULL) || (trp_req_make_wildcard(req)!=TRP_SUCCESS)) {
1463     tr_err("trps_wildcard_route_req: unable to create wildcard TRP request.");
1464     rc=TRP_NOMEM;
1465     goto cleanup;
1466   }
1467
1468   tr_msg_set_trp_req(&msg, req);
1469   encoded=tr_msg_encode(&msg);
1470   if (encoded==NULL) {
1471     tr_err("trps_wildcard_route_req: error encoding wildcard TRP request.");
1472     rc=TRP_ERROR;
1473     goto cleanup;
1474   }
1475
1476   tr_debug("trps_wildcard_route_req: adding message to queue.");
1477   if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS) {
1478     tr_err("trps_wildcard_route_req: error queueing request.");
1479     rc=TRP_ERROR;
1480   } else {
1481     tr_debug("trps_wildcard_route_req: request queued successfully.");
1482     rc=TRP_SUCCESS;
1483   }
1484
1485 cleanup:
1486   if (encoded!=NULL)
1487     tr_msg_free_encoded(encoded);
1488   if (req!=NULL)
1489     trp_req_free(req);
1490
1491   talloc_free(tmp_ctx);
1492   return rc;
1493 }