Gather/send community updates. Refactoring. Builds, not tested.
[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   default:
527     tr_notice("trps_validate_inforec: unsupported record type.");
528     return TRP_UNSUPPORTED;
529   }
530
531   return TRP_SUCCESS;
532 }
533
534 /* link cost to a peer */
535 static unsigned int trps_cost(TRPS_INSTANCE *trps, TR_NAME *peer)
536 {
537   return 1;
538 }
539
540 static unsigned int trps_advertised_metric(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
541 {
542   TRP_ROUTE *entry=trp_rtable_get_entry(trps->rtable, comm, realm, peer);
543   if (entry==NULL)
544     return TRP_METRIC_INFINITY;
545   return trp_route_get_metric(entry) + trps_cost(trps, peer);
546 }
547
548 static int trps_check_feasibility(TRPS_INSTANCE *trps, TR_NAME *realm, TR_NAME *comm, TRP_INFOREC *rec)
549 {
550   unsigned int rec_metric=trp_inforec_get_metric(rec);
551   unsigned int new_metric=0;
552   unsigned int current_metric=0;
553   TR_NAME *next_hop=NULL;
554
555   /* we check these in the validation stage, but just in case... */
556   if (trp_metric_is_invalid(rec_metric))
557     return 0;
558
559   /* retractions (aka infinite metrics) are always feasible */
560   if (trp_metric_is_infinite(rec_metric))
561     return 1;
562
563   /* updates from our current next hop are always feasible*/
564   next_hop=trps_get_next_hop(trps, comm, realm);
565   if ((next_hop!=NULL)
566      && (0==tr_name_cmp(next_hop,trp_inforec_get_next_hop(rec)))) {
567     return 1;
568   }
569     
570
571   /* compare the existing metric we advertise to what we would advertise
572    * if we accept this update */
573   current_metric=trps_advertised_metric(trps, comm, realm, trp_inforec_get_next_hop(rec));
574   new_metric=rec_metric + trps_cost(trps, trp_inforec_get_next_hop(rec));
575   if (new_metric <= current_metric)
576     return 1;
577   else
578     return 0;
579 }
580
581 /* uses memory pointed to by *ts, also returns that value. On error, its contents are {0,0} */
582 static struct timespec *trps_compute_expiry(TRPS_INSTANCE *trps, unsigned int interval, struct timespec *ts)
583 {
584   const unsigned int small_factor=3; /* how many intervals we wait before expiring */
585   if (0!=clock_gettime(CLOCK_REALTIME, ts)) {
586     tr_err("trps_compute_expiry: could not read realtime clock.");
587     ts->tv_sec=0;
588     ts->tv_nsec=0;
589   }
590   ts->tv_sec += small_factor*interval;
591   return ts;
592 }
593
594 static TRP_RC trps_accept_update(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
595 {
596   TRP_ROUTE *entry=NULL;
597
598   entry=trp_rtable_get_entry(trps->rtable,
599                              trp_upd_get_comm(upd),
600                              trp_upd_get_realm(upd),
601                              trp_inforec_get_next_hop(rec));
602   if (entry==NULL) {
603     entry=trp_route_new(NULL);
604     if (entry==NULL) {
605       tr_err("trps_accept_update: unable to allocate new entry.");
606       return TRP_NOMEM;
607     }
608
609     trp_route_set_comm(entry, trp_upd_dup_comm(upd));
610     trp_route_set_realm(entry, trp_upd_dup_realm(upd));
611     trp_route_set_peer(entry, trp_upd_dup_peer(upd));
612     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec));
613     trp_route_set_next_hop(entry, trp_inforec_dup_next_hop(rec));
614     /* TODO: pass next hop port (now defaults to TID_PORT) --jlr */
615     if ((trp_route_get_comm(entry)==NULL)
616        ||(trp_route_get_realm(entry)==NULL)
617        ||(trp_route_get_peer(entry)==NULL)
618        ||(trp_route_get_trust_router(entry)==NULL)
619        ||(trp_route_get_next_hop(entry)==NULL)) {
620       /* at least one field could not be allocated */
621       tr_err("trps_accept_update: unable to allocate all fields for entry.");
622       trp_route_free(entry);
623       return TRP_NOMEM;
624     }
625     trp_rtable_add(trps->rtable, entry);
626   }
627
628   /* We now have an entry in the table, whether it's new or not. Update metric and expiry, unless
629    * the metric is infinity. An infinite metric can only occur here if we just retracted an existing
630    * route (we never accept retractions as new routes), so there is no risk of leaving the expiry
631    * time unset on a new route entry. */
632   tr_debug("trps_accept_update: accepting route update.");
633   trp_route_set_metric(entry, trp_inforec_get_metric(rec));
634   trp_route_set_interval(entry, trp_inforec_get_interval(rec));
635
636   /* check whether the trust router has changed */
637   if (0!=tr_name_cmp(trp_route_get_trust_router(entry),
638                      trp_inforec_get_trust_router(rec))) {
639     /* The name changed. Set this route as triggered. */
640     tr_debug("trps_accept_update: trust router for route changed.");
641     trp_route_set_triggered(entry, 1);
642     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec)); /* frees old name */
643   }
644   if (!trps_route_retracted(trps, entry)) {
645     tr_debug("trps_accept_update: route not retracted, setting expiry timer.");
646     trp_route_set_expiry(entry, trps_compute_expiry(trps,
647                                                      trp_route_get_interval(entry),
648                                                      trp_route_get_expiry(entry)));
649   }
650   return TRP_SUCCESS;
651 }
652
653 static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
654 {
655   unsigned int feas=0;
656   TRP_INFOREC *rec=NULL;
657   TRP_ROUTE *route=NULL;
658
659   if (trps_validate_update(trps, upd) != TRP_SUCCESS) {
660     tr_notice("trps_handle_update: received invalid TRP update.");
661     return TRP_ERROR;
662   }
663
664   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
665     /* validate/sanity check the record update */
666     if (trps_validate_inforec(trps, rec) != TRP_SUCCESS) {
667       tr_notice("trps_handle_update: invalid record in TRP update, discarding entire update.");
668       return TRP_ERROR;
669     }
670   }
671
672   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
673     /* determine feasibility */
674     feas=trps_check_feasibility(trps, trp_upd_get_realm(upd), trp_upd_get_comm(upd), rec);
675     tr_debug("trps_handle_update: record feasibility=%d", feas);
676
677     /* do we have an existing route? */
678     route=trps_get_route(trps,
679                          trp_upd_get_comm(upd),
680                          trp_upd_get_realm(upd),
681                          trp_upd_get_peer(upd));
682     if (route!=NULL) {
683       /* there was a route table entry already */
684       tr_debug("trps_handle_updates: route entry already exists.");
685       if (feas) {
686         /* Update is feasible. Accept it. */
687         trps_accept_update(trps, upd, rec);
688       } else {
689         /* Update is infeasible. Ignore it unless the trust router has changed. */
690         if (0!=tr_name_cmp(trp_route_get_trust_router(route),
691                            trp_inforec_get_trust_router(rec))) {
692           /* the trust router associated with the route has changed, treat update as a retraction */
693           trps_retract_route(trps, route);
694         }
695       }
696     } else {
697       /* No existing route table entry. Ignore it unless it is feasible and not a retraction. */
698       tr_debug("trps_handle_update: no route entry exists yet.");
699       if (feas && trp_metric_is_finite(trp_inforec_get_metric(rec)))
700         trps_accept_update(trps, upd, rec);
701     }
702   }
703   return TRP_SUCCESS;
704 }
705
706 static TRP_RC trps_validate_request(TRPS_INSTANCE *trps, TRP_REQ *req)
707 {
708   if (req==NULL) {
709     tr_notice("trps_validate_request: null TRP request.");
710     return TRP_BADARG;
711   }
712
713   if (trp_req_get_comm(req)==NULL) {
714     tr_notice("trps_validate_request: received TRP request with null community.");
715     return TRP_ERROR;
716   }
717   
718   if (trp_req_get_realm(req)==NULL) {
719     tr_notice("trps_validate_request: received TRP request with null realm.");
720     return TRP_ERROR;
721   }
722   
723   if (trp_req_get_peer(req)==NULL) {
724     tr_notice("trps_validate_request: received TRP request without origin peer information.");
725     return TRP_ERROR;
726   }
727   
728   return TRP_SUCCESS;
729 }
730
731 /* choose the best route to comm/realm, optionally excluding routes to a particular peer */
732 static TRP_ROUTE *trps_find_best_route(TRPS_INSTANCE *trps,
733                                         TR_NAME *comm,
734                                         TR_NAME *realm,
735                                         TR_NAME *exclude_peer)
736 {
737   TRP_ROUTE **entry=NULL;
738   TRP_ROUTE *best=NULL;
739   size_t n_entry=0;
740   unsigned int kk=0;
741   unsigned int kk_min=0;
742   unsigned int min_metric=TRP_METRIC_INFINITY;
743
744   entry=trp_rtable_get_realm_entries(trps->rtable, comm, realm, &n_entry);
745   for (kk=0; kk<n_entry; kk++) {
746     if (trp_route_get_metric(entry[kk]) < min_metric) {
747       if ((exclude_peer==NULL) || (0!=tr_name_cmp(trp_route_get_peer(entry[kk]),
748                                                   exclude_peer))) {
749         kk_min=kk;
750         min_metric=trp_route_get_metric(entry[kk]);
751       } 
752     }
753   }
754   if (trp_metric_is_finite(min_metric))
755     best=entry[kk_min];
756   
757   talloc_free(entry);
758   return best;
759 }
760
761 /* TODO: think this through more carefully. At least ought to add hysteresis
762  * to avoid flapping between routers or routes. */
763 TRP_RC trps_update_active_routes(TRPS_INSTANCE *trps)
764 {
765   size_t n_comm=0, ii=0;
766   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
767   size_t n_realm=0, jj=0;
768   TR_NAME **realm=NULL;
769   TRP_ROUTE *best_route=NULL, *cur_route=NULL;
770   unsigned int best_metric=0, cur_metric=0;
771
772   for (ii=0; ii<n_comm; ii++) {
773     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
774     for (jj=0; jj<n_realm; jj++) {
775       best_route=trps_find_best_route(trps, comm[ii], realm[jj], NULL);
776       if (best_route==NULL)
777         best_metric=TRP_METRIC_INFINITY;
778       else
779         best_metric=trp_route_get_metric(best_route);
780
781       cur_route=trps_get_selected_route(trps, comm[ii], realm[jj]);
782       if (cur_route!=NULL) {
783         cur_metric=trp_route_get_metric(cur_route);
784         if ((best_metric < cur_metric) && (trp_metric_is_finite(best_metric))) {
785           /* The new route has a lower metric than the previous, and is finite. Accept. */
786           trp_route_set_selected(cur_route, 0);
787           trp_route_set_selected(best_route, 1);
788         } else if (!trp_metric_is_finite(cur_metric)) /* rejects infinite or invalid metrics */
789           trp_route_set_selected(cur_route, 0);
790       } else if (trp_metric_is_finite(best_metric)) {
791         trp_route_set_selected(best_route, 1);
792       }
793     }
794     if (realm!=NULL)
795       talloc_free(realm);
796     realm=NULL; n_realm=0;
797   }
798   if (comm!=NULL)
799     talloc_free(comm);
800   comm=NULL; n_comm=0;
801
802   return TRP_SUCCESS;
803 }
804
805 /* true if curtime >= expiry */
806 static int trps_expired(struct timespec *expiry, struct timespec *curtime)
807 {
808   return ((curtime->tv_sec > expiry->tv_sec)
809          || ((curtime->tv_sec == expiry->tv_sec)
810             &&(curtime->tv_nsec >= expiry->tv_nsec)));
811 }
812
813 /* Sweep for expired routes. For each expired route, if its metric is infinite, the route is flushed.
814  * If its metric is finite, the metric is set to infinite and the route's expiration time is updated. */
815 TRP_RC trps_sweep_routes(TRPS_INSTANCE *trps)
816 {
817   struct timespec sweep_time={0,0};
818   TRP_ROUTE **entry=NULL;
819   size_t n_entry=0;
820   size_t ii=0;
821
822   /* use a single time for the entire sweep */
823   if (0!=clock_gettime(CLOCK_REALTIME, &sweep_time)) {
824     tr_err("trps_sweep_routes: could not read realtime clock.");
825     sweep_time.tv_sec=0;
826     sweep_time.tv_nsec=0;
827     return TRP_ERROR;
828   }
829
830   entry=trp_rtable_get_entries(trps->rtable, &n_entry); /* must talloc_free *entry */
831
832   /* loop over the entries */
833   for (ii=0; ii<n_entry; ii++) {
834     if (!trp_route_is_local(entry[ii]) && trps_expired(trp_route_get_expiry(entry[ii]), &sweep_time)) {
835       tr_debug("trps_sweep_routes: route expired.");
836       if (!trp_metric_is_finite(trp_route_get_metric(entry[ii]))) {
837         /* flush route */
838         tr_debug("trps_sweep_routes: metric was infinity, flushing route.");
839         trp_rtable_remove(trps->rtable, entry[ii]); /* entry[ii] is no longer valid */
840         entry[ii]=NULL;
841       } else {
842         /* set metric to infinity and reset timer */
843         tr_debug("trps_sweep_routes: setting metric to infinity and resetting expiry.");
844         trp_route_set_metric(entry[ii], TRP_METRIC_INFINITY);
845         trp_route_set_expiry(entry[ii], trps_compute_expiry(trps,
846                                                              trp_route_get_interval(entry[ii]),
847                                                              trp_route_get_expiry(entry[ii])));
848       }
849     }
850   }
851
852   talloc_free(entry);
853   return TRP_SUCCESS;
854 }
855
856 /* add metrics */
857 static unsigned int trps_metric_add(unsigned int m1, unsigned int m2)
858 {
859   if (trp_metric_is_invalid(m1) || trp_metric_is_invalid(m2))
860     return TRP_METRIC_INVALID;
861
862   if (trp_metric_is_infinite(m1) || trp_metric_is_infinite(m2))
863     return TRP_METRIC_INFINITY;
864
865   if (trp_metric_is_finite(m1+m2))
866     return m1+m2;
867   else
868     return TRP_METRIC_INFINITY;
869 }
870
871 /* convert an rentry into a new trp update info record */
872 static TRP_INFOREC *trps_route_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
873 {
874   TRP_INFOREC *rec=trp_inforec_new(mem_ctx, TRP_INFOREC_TYPE_ROUTE);
875   unsigned int linkcost=0;
876
877   if (rec!=NULL) {
878     if (trp_route_is_local(route))
879       linkcost=0;
880     else {
881       linkcost=trp_peer_get_linkcost(trps_get_peer_by_gssname(trps,
882                                                               trp_route_get_peer(route)));
883     }
884
885     /* Note that we leave the next hop empty since the recipient fills that in.
886      * This is where we add the link cost (currently always 1) to the next peer. */
887     if ((trp_inforec_set_trust_router(rec, trp_route_dup_trust_router(route)) != TRP_SUCCESS)
888        ||(trp_inforec_set_metric(rec,
889                                  trps_metric_add(trp_route_get_metric(route),
890                                                  linkcost)) != TRP_SUCCESS)
891        ||(trp_inforec_set_interval(rec, trps_get_update_interval(trps)) != TRP_SUCCESS)) {
892       tr_err("trps_route_to_inforec: error creating route update.");
893       talloc_free(rec);
894       rec=NULL;
895     }
896   }
897   return rec;
898 }
899
900 static TRP_UPD *trps_route_to_upd(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
901 {
902   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
903   TRP_UPD *upd=trp_upd_new(tmp_ctx);
904   TRP_INFOREC *rec=NULL;
905
906   if (upd==NULL) {
907     tr_err("trps_route_to_upd: could not create update message.");
908     goto cleanup;
909   }
910   trp_upd_set_realm(upd, trp_route_dup_realm(route));
911   if (trp_upd_get_realm(upd)==NULL) {
912     tr_err("trps_route_to_upd: could not copy realm.");
913     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
914     goto cleanup;
915   }
916   trp_upd_set_comm(upd, trp_route_dup_comm(route));
917   if (trp_upd_get_comm(upd)==NULL) {
918     tr_err("trps_route_to_upd: could not copy comm.");
919     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
920     goto cleanup;
921   }
922   rec=trps_route_to_inforec(tmp_ctx, trps, route);
923   if (rec==NULL) {
924     tr_err("trps_route_to_upd: could not create route info record for realm %.*s in comm %.*s.",
925            trp_route_get_realm(route)->len, trp_route_get_realm(route)->buf,
926            trp_route_get_comm(route)->len, trp_route_get_comm(route)->buf);
927     upd=NULL; /* it's till in tmp_ctx, so it will be freed */
928     goto cleanup;
929   }
930   trp_upd_add_inforec(upd, rec);
931
932   /* sucess */
933   talloc_steal(mem_ctx, upd);
934
935 cleanup:
936   talloc_free(tmp_ctx);
937   return upd;
938 }
939
940 /* select the correct route to comm/realm to be announced to peer */
941 static TRP_ROUTE *trps_select_realm_update(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer_gssname)
942 {
943   TRP_ROUTE *route;
944
945   /* Take the currently selected route unless it is through the peer we're sending the update to.
946    * I.e., enforce the split horizon rule. */
947   route=trp_rtable_get_selected_entry(trps->rtable, comm, realm);
948   if (route==NULL) {
949     /* No selected route, this should only happen if the only route has been retracted,
950      * in which case we do not want to advertise it. */
951     return NULL;
952   }
953   tr_debug("trps_select_realm_update: %s vs %s", peer_gssname->buf,
954            trp_route_get_peer(route)->buf);
955   if (0==tr_name_cmp(peer_gssname, trp_route_get_peer(route))) {
956     tr_debug("trps_select_realm_update: matched, finding alternate route");
957     /* the selected entry goes through the peer we're reporting to, choose an alternate */
958     route=trps_find_best_route(trps, comm, realm, peer_gssname);
959     if ((route==NULL) || (!trp_metric_is_finite(trp_route_get_metric(route))))
960       return NULL; /* don't advertise a nonexistent or retracted route */
961   }
962   return route;
963 }
964
965 /* Add TRP_UPD msgs to the updates GPtrArray. Caller needs to arrange for these to be freed. */
966 static TRP_RC trps_select_route_updates_for_peer(TALLOC_CTX *mem_ctx,
967                                                  GPtrArray *updates,
968                                                  TRPS_INSTANCE *trps,
969                                                  TR_NAME *peer_gssname,
970                                                  int triggered)
971 {
972   size_t n_comm=0;
973   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
974   TR_NAME **realm=NULL;
975   size_t n_realm=0;
976   size_t ii=0, jj=0;
977   TRP_ROUTE *best=NULL;
978   TRP_UPD *upd=NULL;
979
980   if (updates==NULL)
981     return TRP_BADARG;
982
983   for (ii=0; ii<n_comm; ii++) {
984     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
985     for (jj=0; jj<n_realm; jj++) {
986       best=trps_select_realm_update(trps, comm[ii], realm[jj], peer_gssname);
987       /* If we found a route, add it to the list. If triggered!=0, then only
988        * add triggered routes. */
989       if ((best!=NULL) && ((!triggered) || trp_route_is_triggered(best))) {
990         upd=trps_route_to_upd(mem_ctx, trps, best);
991         if (upd==NULL) {
992           tr_err("trps_select_route_updates_for_peer: unable to create update message.");
993           continue;
994         }
995         g_ptr_array_add(updates, upd);
996       }
997     }
998     
999     if (realm!=NULL)
1000       talloc_free(realm);
1001     realm=NULL;
1002     n_realm=0;
1003   }
1004
1005   if (comm!=NULL)
1006     talloc_free(comm);
1007   
1008   return TRP_SUCCESS;
1009 }
1010
1011 static TRP_INFOREC *trps_memb_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_COMM_MEMB *memb)
1012 {
1013   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1014   TRP_INFOREC *rec=NULL;
1015   TR_COMM *comm=NULL;
1016
1017   if (memb==NULL)
1018     goto cleanup;
1019
1020   comm=tr_comm_memb_get_comm(memb);
1021   rec=trp_inforec_new(tmp_ctx, TRP_INFOREC_TYPE_COMMUNITY);
1022   if (rec==NULL)
1023     goto cleanup;
1024   
1025   if (TRP_SUCCESS!=trp_inforec_set_comm_type(rec, tr_comm_get_type(comm))) {
1026     rec=NULL;
1027     goto cleanup;
1028   }
1029   
1030   if (TRP_SUCCESS!=trp_inforec_set_role(rec, tr_comm_memb_get_role(memb))) {
1031     rec=NULL;
1032     goto cleanup;
1033   }
1034
1035   if ((TRP_SUCCESS!=trp_inforec_set_apcs(rec,
1036                                          tr_apc_dup(rec, tr_comm_get_apcs(comm)))) ||
1037       (NULL==trp_inforec_get_apcs(rec))) {
1038     rec=NULL;
1039     goto cleanup;
1040   }
1041
1042   if ((NULL!=tr_comm_get_owner_realm(comm)) &&
1043       ( (TRP_SUCCESS!=trp_inforec_set_owner_realm(rec, tr_dup_name(tr_comm_get_owner_realm(comm)))) ||
1044         (NULL==trp_inforec_get_owner_realm(rec)))) {
1045     rec=NULL;
1046     goto cleanup;
1047   }
1048
1049   if ((NULL!=tr_comm_get_owner_contact(comm)) &&
1050       ( (TRP_SUCCESS!=trp_inforec_set_owner_contact(rec, tr_dup_name(tr_comm_get_owner_contact(comm)))) ||
1051         (NULL==trp_inforec_get_owner_contact(rec)))) {
1052     rec=NULL;
1053     goto cleanup;
1054   }
1055
1056   if ((NULL!=tr_comm_memb_get_provenance(memb)) &&
1057       (TRP_SUCCESS!=trp_inforec_set_provenance(rec, tr_comm_memb_get_provenance(memb)))) {
1058     rec=NULL;
1059     goto cleanup;
1060   }
1061
1062   if (TRP_SUCCESS!=trp_inforec_set_interval(rec, tr_comm_memb_get_interval(memb))) {
1063     rec=NULL;
1064     goto cleanup;
1065   }
1066
1067   /* success! */
1068   talloc_steal(mem_ctx, rec);
1069
1070 cleanup:
1071   talloc_free(tmp_ctx);
1072   return rec;
1073 }
1074
1075 /* construct an update with all the inforecs for comm/realm/role to be sent to peer */
1076 static TRP_UPD *trps_comm_update(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_NAME *peer_gssname, TR_COMM *comm, TR_REALM *realm)
1077 {
1078   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1079   TRP_UPD *upd=trp_upd_new(tmp_ctx);
1080   TRP_INFOREC *rec=NULL;
1081   TR_COMM_ITER *iter=NULL;
1082   TR_COMM_MEMB *memb=NULL;
1083
1084   if (upd==NULL)
1085     goto cleanup;
1086   
1087   trp_upd_set_comm(upd, tr_comm_dup_id(comm));
1088   trp_upd_set_realm(upd, tr_realm_dup_id(realm));
1089   /* leave peer empty */
1090
1091   iter=tr_comm_iter_new(tmp_ctx);
1092   if (iter==NULL) {
1093     tr_err("tr_comm_update: unable to allocate iterator.");
1094     upd=NULL;
1095     goto cleanup;
1096   }
1097   
1098   /* now add inforecs */
1099   switch (realm->role) {
1100   case TR_ROLE_IDP:
1101     memb=tr_comm_table_find_idp_memb(trps->ctable,
1102                                      tr_realm_get_id(realm),
1103                                      tr_comm_get_id(comm));
1104     break;
1105   case TR_ROLE_RP:
1106     memb=tr_comm_table_find_rp_memb(trps->ctable,
1107                                     tr_realm_get_id(realm),
1108                                     tr_comm_get_id(comm));
1109     break;
1110   default:
1111     break;
1112   }
1113   if (memb!=NULL) {
1114     for (memb=tr_comm_memb_iter_first(iter, memb);
1115          memb!=NULL;
1116          memb=tr_comm_memb_iter_next(iter)) {
1117       rec=trps_memb_to_inforec(tmp_ctx, trps, memb);
1118       if (rec==NULL) {
1119         tr_err("tr_comm_update: unable to allocate inforec.");
1120         upd=NULL;
1121         goto cleanup;
1122       }
1123       trp_upd_add_inforec(upd, rec);
1124     }
1125   }
1126
1127   if (trp_upd_get_inforec(upd)==NULL)
1128     upd=NULL; /* no inforecs, no reason to send the update */
1129   else
1130     talloc_steal(mem_ctx, upd); /* success! */
1131
1132 cleanup:
1133   talloc_free(tmp_ctx);
1134   return upd;
1135 }
1136
1137 /* Find all community updates to send to a peer and add these as TR_UPD records
1138  * to the updates GPtrArray. */
1139 static TRP_RC trps_select_comm_updates_for_peer(TALLOC_CTX *mem_ctx, GPtrArray *updates, TRPS_INSTANCE *trps, TR_NAME *peer_gssname)
1140 {
1141   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1142   TR_COMM_ITER *comm_iter=NULL;
1143   TR_COMM *comm=NULL;
1144   TR_COMM_ITER *realm_iter=NULL;
1145   TR_REALM *realm=NULL;
1146   TRP_UPD *upd=NULL;
1147   TRP_RC rc=TRP_ERROR;
1148   
1149   comm_iter=tr_comm_iter_new(tmp_ctx);
1150   realm_iter=tr_comm_iter_new(tmp_ctx);
1151   if ((comm_iter==NULL) || (realm_iter==NULL)) {
1152     tr_err("trps_select_comm_updates_for_peer: unable to allocate iterator.");
1153     rc=TRP_NOMEM;
1154     goto cleanup;
1155   }
1156
1157   /* do every community */
1158   for (comm=tr_comm_table_iter_first(comm_iter, trps->ctable);
1159        comm!=NULL;
1160        comm=tr_comm_table_iter_next(comm_iter)) {
1161     /* do every realm in this community */
1162     for (realm=tr_realm_iter_first(realm_iter, trps->ctable, tr_comm_get_id(comm));
1163          realm!=NULL;
1164          realm=tr_realm_iter_next(realm_iter)) {
1165       /* get the update for this comm/realm */
1166       upd=trps_comm_update(tmp_ctx, trps, peer_gssname, comm, realm);
1167       if (upd!=NULL) {
1168         g_ptr_array_add(updates, upd);
1169       }
1170     }
1171   }
1172
1173   /* move anything needed into mem_ctx */
1174   
1175
1176 cleanup:
1177   talloc_free(tmp_ctx);
1178   return rc;
1179 }
1180
1181
1182 /* helper for trps_update_one_peer. Frees the TRP_UPD pointed to by a GPtrArray element */
1183 static void trps_trp_upd_destroy(gpointer data)
1184 {
1185   trp_upd_free((TRP_UPD *)data);
1186 }
1187
1188 /* all routes/communities to a single peer, unless comm/realm are specified (both or neither must be NULL) */
1189 static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
1190                                    TRP_PEER *peer,
1191                                    TRP_UPDATE_TYPE update_type,
1192                                    TR_NAME *comm,
1193                                    TR_NAME *realm)
1194 {
1195   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1196   TR_MSG msg; /* not a pointer! */
1197   TRP_UPD *upd=NULL;
1198   TRP_ROUTE *route=NULL;
1199   size_t ii=0;
1200   char *encoded=NULL;
1201   TRP_RC rc=TRP_ERROR;
1202   TR_NAME *peer_label=trp_peer_get_label(peer);
1203   GPtrArray *updates=g_ptr_array_new_with_free_func(trps_trp_upd_destroy);
1204
1205   if (updates==NULL) {
1206     tr_err("trps_update_one_peer: unable to allocate updates array.");
1207     rc=TRP_NOMEM;
1208     goto cleanup;
1209   }
1210
1211   switch (update_type) {
1212   case TRP_UPDATE_TRIGGERED:
1213     tr_debug("trps_update_one_peer: preparing triggered update for %.*s",
1214              peer_label->len, peer_label->buf);
1215     break;
1216   case TRP_UPDATE_SCHEDULED:
1217     tr_debug("trps_update_one_peer: preparing scheduled update for %.*s",
1218              peer_label->len, peer_label->buf);
1219     break;
1220   case TRP_UPDATE_REQUESTED:
1221     tr_debug("trps_update_one_peer: preparing requested update for %.*s",
1222              peer_label->len, peer_label->buf);
1223     break;
1224   default:
1225     tr_err("trps_update_one_peer: invalid update type requested.");
1226     rc=TRP_BADARG;
1227     goto cleanup;
1228   }
1229
1230   /* First, gather route updates. */
1231   if ((comm==NULL) && (realm==NULL)) {
1232     /* do all realms */
1233     rc=trps_select_route_updates_for_peer(tmp_ctx,
1234                                           updates,
1235                                           trps,
1236                                           peer_label,
1237                                           update_type==TRP_UPDATE_TRIGGERED);
1238   } else if ((comm!=NULL) && (realm!=NULL)) {
1239     /* a single community/realm was requested */
1240     route=trps_select_realm_update(trps, comm, realm, peer_label);
1241     if (route==NULL) {
1242       /* we have no actual update to send back, MUST send a retraction */
1243       tr_debug("trps_update_one_peer: community/realm without route requested, sending mandatory retraction.");
1244       route=trp_route_new(tmp_ctx);
1245       trp_route_set_comm(route, tr_dup_name(comm));
1246       trp_route_set_realm(route, tr_dup_name(realm));
1247       trp_route_set_peer(route, tr_new_name(""));
1248       trp_route_set_metric(route, TRP_METRIC_INFINITY);
1249       trp_route_set_trust_router(route, tr_new_name(""));
1250       trp_route_set_next_hop(route, tr_new_name(""));
1251     }
1252     upd=trps_route_to_upd(tmp_ctx, trps, route);
1253     if (upd==NULL) {
1254       tr_err("trps_update_one_peer: unable to allocate route update.");
1255       rc=TRP_NOMEM;
1256       goto cleanup;
1257     }
1258     g_ptr_array_add(updates, upd);
1259   } else {
1260     tr_err("trps_update_one_peer: error: only comm or realm was specified. Need both or neither.");
1261     rc=TRP_ERROR;
1262     goto cleanup;
1263   }
1264
1265   /* Second, gather community updates */
1266   rc=trps_select_comm_updates_for_peer(tmp_ctx, updates, trps, peer_label);
1267
1268   /* see if we have anything to send */
1269   if (updates->len<=0)
1270     tr_debug("trps_update_one_peer: no updates for %.*s", peer_label->len, peer_label->buf);
1271   else {
1272     tr_debug("trps_update_one_peer: sending %d update messages.", updates->len);
1273     for (ii=0; NULL!=(upd=(TRP_UPD *)g_ptr_array_index(updates, ii)); ii++) {
1274       /* now encode the update message */
1275       tr_msg_set_trp_upd(&msg, upd);
1276       encoded=tr_msg_encode(&msg);
1277       if (encoded==NULL) {
1278         tr_err("trps_update_one_peer: error encoding update.");
1279         rc=TRP_ERROR;
1280         goto cleanup;
1281       }
1282
1283       tr_debug("trps_update_one_peer: adding message to queue.");
1284       if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
1285         tr_err("trps_update_one_peer: error queueing update.");
1286       else
1287         tr_debug("trps_update_one_peer: update queued successfully.");
1288
1289       tr_msg_free_encoded(encoded);
1290       encoded=NULL;
1291     }
1292   }
1293
1294   rc=TRP_SUCCESS;
1295
1296 cleanup:
1297   if (updates!=NULL)
1298     g_ptr_array_free(updates, TRUE); /* frees any TRP_UPD records */
1299   talloc_free(tmp_ctx);
1300   return rc;
1301 }
1302
1303 /* all routes/communities to all peers */
1304 TRP_RC trps_update(TRPS_INSTANCE *trps, TRP_UPDATE_TYPE update_type)
1305 {
1306   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1307   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
1308   TRP_PEER *peer=NULL;
1309   TRP_RC rc=TRP_SUCCESS;
1310
1311   if (trps->ptable==NULL)
1312     return TRP_SUCCESS; /* no peers, nothing to do */
1313
1314   if (iter==NULL) {
1315     tr_err("trps_update: failed to allocate peer table iterator.");
1316     talloc_free(tmp_ctx);
1317     return TRP_NOMEM;
1318   }
1319
1320   for (peer=trp_ptable_iter_first(iter, trps->ptable);
1321        peer!=NULL && rc==TRP_SUCCESS;
1322        peer=trp_ptable_iter_next(iter))
1323   {
1324     if (!trps_peer_connected(trps, peer)) {
1325       TR_NAME *peer_label=trp_peer_get_label(peer);
1326       tr_debug("trps_update: no TRP connection to %.*s, skipping.",
1327                peer_label->len, peer_label->buf);
1328       continue;
1329     }
1330     rc=trps_update_one_peer(trps, peer, update_type, NULL, NULL);
1331   }
1332
1333   tr_debug("trps_update: rc=%u after attempting update.", rc);
1334   trp_ptable_iter_free(iter);
1335   trp_rtable_clear_triggered(trps->rtable); /* don't re-send triggered updates */
1336   talloc_free(tmp_ctx);
1337   return rc;
1338 }        
1339
1340 TRP_RC trps_add_route(TRPS_INSTANCE *trps, TRP_ROUTE *route)
1341 {
1342   trp_rtable_add(trps->rtable, route); /* should return status */
1343   return TRP_SUCCESS; 
1344 }
1345
1346 /* steals the peer object */
1347 TRP_RC trps_add_peer(TRPS_INSTANCE *trps, TRP_PEER *peer)
1348 {
1349   if (trps->ptable==NULL) {
1350     trps->ptable=trp_ptable_new(trps);
1351     if (trps->ptable==NULL)
1352       return TRP_NOMEM;
1353   }
1354   return trp_ptable_add(trps->ptable, peer);
1355 }
1356
1357 TRP_PEER *trps_get_peer_by_gssname(TRPS_INSTANCE *trps, TR_NAME *gssname)
1358 {
1359   if (trps->ptable==NULL)
1360     return NULL;
1361
1362   return trp_ptable_find_gss_name(trps->ptable, gssname);
1363 }
1364
1365 TRP_PEER *trps_get_peer_by_servicename(TRPS_INSTANCE *trps, TR_NAME *servicename)
1366 {
1367   if (trps->ptable==NULL)
1368     return NULL;
1369
1370   return trp_ptable_find_servicename(trps->ptable, servicename);
1371 }
1372
1373 int trps_peer_connected(TRPS_INSTANCE *trps, TRP_PEER *peer)
1374 {
1375   TRPC_INSTANCE *trpc=trps_find_trpc(trps, peer);
1376   if (trpc==NULL)
1377     return 0;
1378
1379   if (trpc_get_status(trpc)==TRP_CONNECTION_UP)
1380     return 1;
1381   else
1382     return 0;
1383 }
1384
1385
1386 static TRP_RC trps_handle_request(TRPS_INSTANCE *trps, TRP_REQ *req)
1387 {
1388   TR_NAME *comm=NULL;
1389   TR_NAME *realm=NULL;
1390
1391   tr_debug("trps_handle_request: handling TRP request.");
1392
1393   if (trps_validate_request(trps, req) != TRP_SUCCESS) {
1394     tr_notice("trps_handle_request: received invalid TRP request.");
1395     return TRP_ERROR;
1396   }
1397
1398   if (!trp_req_is_wildcard(req)) {
1399     comm=trp_req_get_comm(req);
1400     realm=trp_req_get_realm(req);
1401     tr_debug("trps_handle_request: route for %.*s/%.*s requested.",
1402              comm->len, comm->buf, realm->len, realm->buf);
1403   } else {
1404     tr_debug("trps_handle_request: all routes requested.");
1405     /* leave comm/realm NULL */
1406   }
1407   return trps_update_one_peer(trps,
1408                               trps_get_peer_by_gssname(trps, trp_req_get_peer(req)),
1409                               TRP_UPDATE_REQUESTED,
1410                               comm,
1411                               realm);
1412 }
1413
1414
1415 TRP_RC trps_handle_tr_msg(TRPS_INSTANCE *trps, TR_MSG *tr_msg)
1416 {
1417   TRP_RC rc=TRP_ERROR;
1418
1419   switch (tr_msg_get_msg_type(tr_msg)) {
1420   case TRP_UPDATE:
1421     rc=trps_handle_update(trps, tr_msg_get_trp_upd(tr_msg));
1422     if (rc==TRP_SUCCESS) {
1423       rc=trps_update_active_routes(trps);
1424       trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
1425     }
1426     return rc;
1427
1428   case TRP_REQUEST:
1429     rc=trps_handle_request(trps, tr_msg_get_trp_req(tr_msg));
1430     return rc;
1431
1432   default:
1433     /* unknown error or one we don't care about (e.g., TID messages) */
1434     return TRP_ERROR;
1435   }
1436 }
1437
1438 /* send wildcard route request to a peer */
1439 TRP_RC trps_wildcard_route_req(TRPS_INSTANCE *trps, TR_NAME *peer_servicename)
1440 {
1441   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1442   TRP_PEER *peer=trps_get_peer_by_servicename(trps, peer_servicename);
1443   TR_MSG msg; /* not a pointer */
1444   TRP_REQ *req=trp_req_new(tmp_ctx);
1445   char *encoded=NULL;
1446   TRP_RC rc=TRP_ERROR;
1447
1448   if (peer==NULL) {
1449     tr_err("trps_wildcard_route_req: unknown peer (%.*s).", peer_servicename->len, peer_servicename->buf);
1450     rc=TRP_BADARG;
1451     goto cleanup;
1452   }
1453   if ((req==NULL) || (trp_req_make_wildcard(req)!=TRP_SUCCESS)) {
1454     tr_err("trps_wildcard_route_req: unable to create wildcard TRP request.");
1455     rc=TRP_NOMEM;
1456     goto cleanup;
1457   }
1458
1459   tr_msg_set_trp_req(&msg, req);
1460   encoded=tr_msg_encode(&msg);
1461   if (encoded==NULL) {
1462     tr_err("trps_wildcard_route_req: error encoding wildcard TRP request.");
1463     rc=TRP_ERROR;
1464     goto cleanup;
1465   }
1466
1467   tr_debug("trps_wildcard_route_req: adding message to queue.");
1468   if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS) {
1469     tr_err("trps_wildcard_route_req: error queueing request.");
1470     rc=TRP_ERROR;
1471   } else {
1472     tr_debug("trps_wildcard_route_req: request queued successfully.");
1473     rc=TRP_SUCCESS;
1474   }
1475
1476 cleanup:
1477   if (encoded!=NULL)
1478     tr_msg_free_encoded(encoded);
1479   if (req!=NULL)
1480     trp_req_free(req);
1481
1482   talloc_free(tmp_ctx);
1483   return rc;
1484 }