Initialize route table with local routes. Fix bugs.
[trust_router.git] / trp / trps.c
1 #include <fcntl.h>
2 #include <talloc.h>
3 #include <errno.h>
4 #include <unistd.h>
5 #include <sys/time.h>
6
7 #include <gsscon.h>
8 #include <tr_rp.h>
9 #include <trust_router/tr_name.h>
10 #include <trp_internal.h>
11 #include <trp_ptable.h>
12 #include <trp_rtable.h>
13 #include <tr_debug.h>
14
15
16 static int trps_destructor(void *object)
17 {
18   TRPS_INSTANCE *trps=talloc_get_type_abort(object, TRPS_INSTANCE);
19   if (trps->rtable!=NULL)
20     trp_rtable_free(trps->rtable);
21   return 0;
22 }
23
24 TRPS_INSTANCE *trps_new (TALLOC_CTX *mem_ctx)
25 {
26   TRPS_INSTANCE *trps=talloc(mem_ctx, TRPS_INSTANCE);
27   if (trps!=NULL)  {
28     trps->hostname=NULL;
29     trps->port=0;
30     trps->cookie=NULL;
31     trps->conn=NULL;
32     trps->trpc=NULL;
33     trps->update_interval=(struct timeval){0,0};
34     trps->sweep_interval=(struct timeval){0,0};
35
36     trps->mq=tr_mq_new(trps);
37     if (trps->mq==NULL) {
38       /* failed to allocate mq */
39       talloc_free(trps);
40       return NULL;
41     }
42
43     trps->ptable=trp_ptable_new(trps);
44     if (trps->ptable==NULL) {
45       /* failed to allocate ptable */
46       talloc_free(trps);
47       return NULL;
48     }
49
50     trps->rtable=NULL;
51     if (trps_init_rtable(trps) != TRP_SUCCESS) {
52       /* failed to allocate rtable */
53       talloc_free(trps);
54       return NULL;
55     }
56
57     talloc_set_destructor((void *)trps, trps_destructor);
58   }
59   return trps;
60 }
61
62 /* create a new route table, first discarding an old one if necessary */
63 TRP_RC trps_init_rtable(TRPS_INSTANCE *trps)
64 {
65   if (trps->rtable != NULL) {
66     trp_rtable_free(trps->rtable);
67     trps->rtable=NULL;
68   }
69
70   trps->rtable=trp_rtable_new();
71   if (trps->rtable==NULL) {
72     return TRP_NOMEM;
73   }
74   return TRP_SUCCESS;
75 }
76
77 void trps_clear_rtable(TRPS_INSTANCE *trps)
78 {
79   trp_rtable_clear(trps->rtable);
80 }
81
82 void trps_free (TRPS_INSTANCE *trps)
83 {
84   if (trps!=NULL)
85     talloc_free(trps);
86 }
87
88 TR_MQ_MSG *trps_mq_pop(TRPS_INSTANCE *trps)
89 {
90   return tr_mq_pop(trps->mq);
91 }
92
93 void trps_mq_append(TRPS_INSTANCE *trps, TR_MQ_MSG *msg)
94 {
95   tr_mq_append(trps->mq, msg);
96 }
97
98 unsigned int trps_get_connect_interval(TRPS_INSTANCE *trps)
99 {
100   return trps->connect_interval.tv_sec;
101 }
102
103 void trps_set_connect_interval(TRPS_INSTANCE *trps, unsigned int interval)
104 {
105   trps->connect_interval.tv_sec=interval;
106   trps->connect_interval.tv_usec=0;
107 }
108
109 unsigned int trps_get_update_interval(TRPS_INSTANCE *trps)
110 {
111   return trps->update_interval.tv_sec;
112 }
113
114 void trps_set_update_interval(TRPS_INSTANCE *trps, unsigned int interval)
115 {
116   trps->update_interval.tv_sec=interval;
117   trps->update_interval.tv_usec=0;
118 }
119
120 unsigned int trps_get_sweep_interval(TRPS_INSTANCE *trps)
121 {
122   return trps->sweep_interval.tv_sec;
123 }
124
125 void trps_set_sweep_interval(TRPS_INSTANCE *trps, unsigned int interval)
126 {
127   trps->sweep_interval.tv_sec=interval;
128   trps->sweep_interval.tv_usec=0;
129 }
130
131 TRPC_INSTANCE *trps_find_trpc(TRPS_INSTANCE *trps, TRP_PEER *peer)
132 {
133   TRPC_INSTANCE *cur=NULL;
134   TR_NAME *name=NULL;
135   TR_NAME *peer_gssname=trp_peer_get_gssname(peer);
136
137   for (cur=trps->trpc; cur!=NULL; cur=trpc_get_next(cur)) {
138     name=trpc_get_gssname(cur);
139     if ((name!=NULL) && (0==tr_name_cmp(peer_gssname, name))) {
140       break;
141     }
142   }
143   tr_free_name(peer_gssname);
144   return cur;
145 }
146
147 void trps_add_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *new)
148 {
149   if (trps->conn==NULL)
150     trps->conn=new;
151   else
152     trp_connection_append(trps->conn, new);
153
154   talloc_steal(trps, new);
155 }
156
157 /* ok to call more than once; guarantees connection no longer in the list.
158  * Caller is responsible for freeing the removed element afterwards.  */
159 void trps_remove_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *remove)
160 {
161   trps->conn=trp_connection_remove(trps->conn, remove);
162 }
163
164 void trps_add_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *trpc)
165 {
166   if (trps->trpc==NULL)
167     trps->trpc=trpc;
168   else
169     trpc_append(trps->trpc, trpc);
170
171   talloc_steal(trps, trpc);
172 }
173
174 /* ok to call more than once; guarantees trpc no longer in the list.
175  * Caller is responsible for freeing the removed element afterwards.  */
176 void trps_remove_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *remove)
177 {
178   trps->trpc=trpc_remove(trps->trpc, remove);
179 }
180
181 TRP_RC trps_send_msg(TRPS_INSTANCE *trps, TRP_PEER *peer, const char *msg)
182 {
183   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
184   TR_MQ_MSG *mq_msg=NULL;
185   char *msg_dup=NULL;
186   TRP_RC rc=TRP_ERROR;
187   TRPC_INSTANCE *trpc=NULL;
188
189   /* get the connection for this peer */
190   trpc=trps_find_trpc(trps, peer);
191   if ((trpc==NULL) || (trpc_get_status(trps->trpc)!=TRP_CONNECTION_UP)) {
192     /* We could just let these sit on the queue in the hopes that a connection
193      * is eventually established. However, we'd then have to ensure the queue
194      * didn't keep growing, etc. */
195     tr_warning("trps_send_msg: skipping message queued while TRPC connection not up.");
196   } else {
197     mq_msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_SEND);
198     msg_dup=talloc_strdup(mq_msg, msg); /* get local copy in mq_msg context */
199     tr_mq_msg_set_payload(mq_msg, msg_dup, NULL); /* no need for a free() func */
200     trpc_mq_append(trpc, mq_msg);
201     rc=TRP_SUCCESS;
202   }
203   talloc_free(tmp_ctx);
204   return rc;
205 }
206
207 static int trps_listen (TRPS_INSTANCE *trps, int port) 
208 {
209   int rc = 0;
210   int conn = -1;
211   int optval = 1;
212
213   union {
214     struct sockaddr_storage storage;
215     struct sockaddr_in in4;
216   } addr;
217
218   struct sockaddr_in *saddr = (struct sockaddr_in *) &addr.in4;
219
220   saddr->sin_port = htons (port);
221   saddr->sin_family = AF_INET;
222   saddr->sin_addr.s_addr = INADDR_ANY;
223
224   if (0 > (conn = socket (AF_INET, SOCK_STREAM, 0)))
225     return conn;
226
227   setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
228
229   if (0 > (rc = bind (conn, (struct sockaddr *) saddr, sizeof(struct sockaddr_in))))
230     return rc;
231
232   if (0 > (rc = listen(conn, 512)))
233     return rc;
234
235   tr_debug("trps_listen: TRP Server listening on port %d", port);
236   return conn;
237 }
238
239 #if 0 /* remove this if I forget to do so */
240 /* returns EACCES if authorization is denied */
241 int trps_auth_cb(gss_name_t clientName, gss_buffer_t displayName, void *data)
242 {
243   TRPS_INSTANCE *trps = (TRPS_INSTANCE *)data;
244   int result=0;
245
246   if (0!=trps->auth_handler(clientName, displayName, trps->cookie)) {
247     tr_debug("trps_auth_cb: client '%.*s' denied authorization.", displayName->length, displayName->value);
248     result=EACCES; /* denied */
249   }
250
251   return result;
252 }
253 #endif 
254
255 /* get the currently selected route if available */
256 TRP_RENTRY *trps_get_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
257 {
258   return trp_rtable_get_entry(trps->rtable, comm, realm, peer);
259 }
260
261 TRP_RENTRY *trps_get_selected_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
262 {
263   return trp_rtable_get_selected_entry(trps->rtable, comm, realm);
264 }
265
266 /* copy the result if you want to keep it */
267 TR_NAME *trps_get_next_hop(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
268 {
269   TRP_RENTRY *route=trps_get_selected_route(trps, comm, realm);
270   if (route==NULL)
271     return NULL;
272
273   return trp_rentry_get_next_hop(route);
274 }
275
276
277 /* mark a route as retracted */
278 static void trps_retract_route(TRPS_INSTANCE *trps, TRP_RENTRY *entry)
279 {
280   trp_rentry_set_metric(entry, TRP_METRIC_INFINITY);
281 }
282
283 /* is this route retracted? */
284 static int trps_route_retracted(TRPS_INSTANCE *trps, TRP_RENTRY *entry)
285 {
286   return (trp_metric_is_infinite(trp_rentry_get_metric(entry)));
287 }
288
289 static TRP_RC trps_read_message(TRPS_INSTANCE *trps, TRP_CONNECTION *conn, TR_MSG **msg)
290 {
291   int err=0;
292   char *buf=NULL;
293   size_t buflen = 0;
294   TR_NAME *peer=NULL;
295
296   tr_debug("trps_read_message: started");
297   if (err = gsscon_read_encrypted_token(trp_connection_get_fd(conn),
298                                        *(trp_connection_get_gssctx(conn)), 
299                                        &buf,
300                                        &buflen)) {
301     tr_debug("trps_read_message: error");
302     if (buf)
303       free(buf);
304     return TRP_ERROR;
305   }
306
307   tr_debug("trps_read_message(): Request Received, %u bytes.", (unsigned) buflen);
308   tr_debug("trps_read_message(): %.*s", buflen, buf);
309
310   *msg=tr_msg_decode(buf, buflen);
311   free(buf);
312   if (*msg==NULL)
313     return TRP_NOPARSE;
314
315   peer=trp_connection_get_peer(conn);
316   /* verify we received a message we support, otherwise drop it now */
317   switch (tr_msg_get_msg_type(*msg)) {
318   case TRP_UPDATE:
319     trp_upd_set_peer(tr_msg_get_trp_upd(*msg), tr_dup_name(peer));
320     break;
321
322   case TRP_REQUEST:
323     trp_req_set_peer(tr_msg_get_trp_req(*msg), tr_dup_name(peer));
324     break;
325
326   default:
327     tr_debug("trps_read_message: received unsupported message from %.*s", peer->len, peer->buf);
328     tr_msg_free_decoded(*msg);
329     *msg=NULL;
330     return TRP_UNSUPPORTED;
331   }
332   
333   return TRP_SUCCESS;
334 }
335
336 int trps_get_listener(TRPS_INSTANCE *trps,
337                       TRPS_MSG_FUNC msg_handler,
338                       TRP_AUTH_FUNC auth_handler,
339                       const char *hostname,
340                       unsigned int port,
341                       void *cookie)
342 {
343   int listen = -1;
344
345   if (0 > (listen = trps_listen(trps, port))) {
346     char errbuf[256];
347     if (0 == strerror_r(errno, errbuf, 256)) {
348       tr_debug("trps_get_listener: Error opening port %d: %s.", port, errbuf);
349     } else {
350       tr_debug("trps_get_listener: Unknown error openining port %d.", port);
351     }
352   } 
353
354   if (listen > 0) {
355     /* opening port succeeded */
356     tr_debug("trps_get_listener: Opened port %d.", port);
357     
358     /* make this socket non-blocking */
359     if (0 != fcntl(listen, F_SETFL, O_NONBLOCK)) {
360       tr_debug("trps_get_listener: Error setting O_NONBLOCK.");
361       close(listen);
362       listen=-1;
363     }
364   }
365
366   if (listen > 0) {
367     /* store the caller's request handler & cookie */
368     trps->msg_handler = msg_handler;
369     trps->auth_handler = auth_handler;
370     trps->hostname = talloc_strdup(trps, hostname);
371     trps->port = port;
372     trps->cookie = cookie;
373   }
374
375   return listen;
376 }
377
378 void trps_handle_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
379 {
380   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
381   TR_MSG *msg=NULL;
382   TRP_RC rc=TRP_ERROR;
383
384   /* try to establish a GSS context */
385   if (0!=trp_connection_auth(conn, trps->auth_handler, trps->cookie)) {
386     tr_notice("tr_trps_conn_thread: failed to authorize connection");
387     pthread_exit(NULL);
388   }
389   tr_notice("trps_handle_connection: authorized connection");
390   
391   /* loop as long as the connection exists */
392   while (trp_connection_get_status(conn)==TRP_CONNECTION_UP) {
393     rc=trps_read_message(trps, conn, &msg);
394     switch(rc) {
395     case TRP_SUCCESS:
396       trps->msg_handler(trps, conn, msg); /* send the TR_MSG off to the callback */
397       break;
398
399     case TRP_ERROR:
400       trp_connection_close(conn);
401       break;
402
403     default:
404       tr_debug("trps_handle_connection: trps_read_message failed (%d)", rc);
405     }
406   }
407
408   tr_debug("trps_handle_connection: connection closed.");
409   talloc_free(tmp_ctx);
410 }
411
412 static TRP_RC trps_validate_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
413 {
414   if (trp_upd_get_inforec(upd)==NULL) {
415     tr_notice("trps_validate_update: received TRP update with no info records.");
416     return TRP_ERROR;
417   }
418
419   if (trp_upd_get_peer(upd)==NULL) {
420     tr_notice("trps_validate_update: received TRP update without origin peer information.");
421     return TRP_ERROR;
422   }
423   
424   return TRP_SUCCESS;
425 }
426
427 /* ensure that the update could be accepted if feasible */
428 static TRP_RC trps_validate_inforec(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
429 {
430   switch(trp_inforec_get_type(rec)) {
431   case TRP_INFOREC_TYPE_ROUTE:
432     if ((trp_inforec_get_comm(rec)==NULL)
433        || (trp_inforec_get_realm(rec)==NULL)
434        || (trp_inforec_get_trust_router(rec)==NULL)
435        || (trp_inforec_get_next_hop(rec)==NULL)) {
436       tr_debug("trps_validate_inforec: missing record info.");
437       return TRP_ERROR;
438     }
439
440     /* check for valid metric */
441     if (trp_metric_is_invalid(trp_inforec_get_metric(rec))) {
442       tr_debug("trps_validate_inforec: invalid metric (%u).", trp_inforec_get_metric(rec));
443       return TRP_ERROR;
444     }
445
446     /* check for valid interval */
447     if (trp_inforec_get_interval(rec)==TRP_INTERVAL_INVALID) {
448       tr_debug("trps_validate_inforec: invalid interval.");
449       return TRP_ERROR;
450     }
451     break;
452
453   default:
454     tr_notice("trps_validate_inforec: unsupported record type.");
455     return TRP_UNSUPPORTED;
456   }
457
458   return TRP_SUCCESS;
459 }
460
461 /* link cost to a peer */
462 static unsigned int trps_cost(TRPS_INSTANCE *trps, TR_NAME *peer)
463 {
464   return 1;
465 }
466
467 static unsigned int trps_advertised_metric(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
468 {
469   TRP_RENTRY *entry=trp_rtable_get_entry(trps->rtable, comm, realm, peer);
470   if (entry==NULL)
471     return TRP_METRIC_INFINITY;
472   return trp_rentry_get_metric(entry) + trps_cost(trps, peer);
473 }
474
475 static int trps_check_feasibility(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
476 {
477   unsigned int rec_metric=trp_inforec_get_metric(rec);
478   unsigned int new_metric=0;
479   unsigned int current_metric=0;
480   TR_NAME *next_hop=NULL;
481
482   /* we check these in the validation stage, but just in case... */
483   if (trp_metric_is_invalid(rec_metric))
484     return 0;
485
486   /* retractions (aka infinite metrics) are always feasible */
487   if (trp_metric_is_infinite(rec_metric))
488     return 1;
489
490   /* updates from our current next hop are always feasible*/
491   next_hop=trps_get_next_hop(trps,
492                              trp_inforec_get_comm(rec),
493                              trp_inforec_get_realm(rec));;
494   if ((next_hop!=NULL)
495      && (0==tr_name_cmp(next_hop,trp_inforec_get_next_hop(rec)))) {
496     return 1;
497   }
498     
499
500   /* compare the existing metric we advertise to what we would advertise
501    * if we accept this update */
502   current_metric=trps_advertised_metric(trps,
503                                         trp_inforec_get_comm(rec),
504                                         trp_inforec_get_realm(rec),
505                                         trp_inforec_get_next_hop(rec));
506   new_metric=rec_metric + trps_cost(trps, trp_inforec_get_next_hop(rec));
507   if (new_metric <= current_metric)
508     return 1;
509   else
510     return 0;
511 }
512
513 /* uses memory pointed to by *ts, also returns that value. On error, its contents are {0,0} */
514 static struct timespec *trps_compute_expiry(TRPS_INSTANCE *trps, unsigned int interval, struct timespec *ts)
515 {
516   const unsigned int small_factor=3; /* how many intervals we wait before expiring */
517   if (0!=clock_gettime(CLOCK_REALTIME, ts)) {
518     tr_err("trps_compute_expiry: could not read realtime clock.");
519     ts->tv_sec=0;
520     ts->tv_nsec=0;
521   }
522   ts->tv_sec += small_factor*interval;
523   return ts;
524 }
525
526 static TRP_RC trps_accept_update(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
527 {
528   TRP_RENTRY *entry=NULL;
529
530   entry=trp_rtable_get_entry(trps->rtable,
531                              trp_inforec_get_comm(rec),
532                              trp_inforec_get_realm(rec),
533                              trp_inforec_get_next_hop(rec));
534   if (entry==NULL) {
535     entry=trp_rentry_new(NULL);
536     if (entry==NULL) {
537       tr_err("trps_accept_update: unable to allocate new entry.");
538       return TRP_NOMEM;
539     }
540
541     trp_rentry_set_apc(entry, tr_dup_name(trp_inforec_get_comm(rec)));
542     trp_rentry_set_realm(entry, tr_dup_name(trp_inforec_get_realm(rec)));
543     trp_rentry_set_peer(entry, tr_dup_name(trp_inforec_get_next_hop(rec)));
544     trp_rentry_set_trust_router(entry, tr_dup_name(trp_inforec_get_trust_router(rec)));
545     trp_rentry_set_next_hop(entry, tr_dup_name(trp_inforec_get_next_hop(rec)));
546     if ((trp_rentry_get_apc(entry)==NULL)
547        ||(trp_rentry_get_realm(entry)==NULL)
548        ||(trp_rentry_get_peer(entry)==NULL)
549        ||(trp_rentry_get_trust_router(entry)==NULL)
550        ||(trp_rentry_get_next_hop(entry)==NULL)) {
551       /* at least one field could not be allocated */
552       tr_err("trps_accept_update: unable to allocate all fields for entry.");
553       trp_rentry_free(entry);
554       return TRP_NOMEM;
555     }
556     trp_rtable_add(trps->rtable, entry);
557   }
558
559   /* We now have an entry in the table, whether it's new or not. Update metric and expiry, unless
560    * the metric is infinity. An infinite metric can only occur here if we just retracted an existing
561    * route (we never accept retractions as new routes), so there is no risk of leaving the expiry
562    * time unset on a new route entry. */
563   tr_debug("trps_accept_update: accepting route update.");
564   trp_rentry_set_metric(entry, trp_inforec_get_metric(rec));
565   trp_rentry_set_interval(entry, trp_inforec_get_interval(rec));
566   if (!trps_route_retracted(trps, entry)) {
567     tr_debug("trps_accept_update: route not retracted, setting expiry timer.");
568     trp_rentry_set_expiry(entry, trps_compute_expiry(trps,
569                                                      trp_rentry_get_interval(entry),
570                                                      trp_rentry_get_expiry(entry)));
571   }
572   return TRP_SUCCESS;
573 }
574
575 /* TODO: handle community updates */
576 static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
577 {
578   unsigned int feas=0;
579   TRP_INFOREC *rec=NULL;
580   TRP_RENTRY *route=NULL;
581
582   if (trps_validate_update(trps, upd) != TRP_SUCCESS) {
583     tr_notice("trps_handle_update: received invalid TRP update.");
584     return TRP_ERROR;
585   }
586
587   rec=trp_upd_get_inforec(upd);
588   for (;rec!=NULL; rec=trp_inforec_get_next(rec)) {
589     /* validate/sanity check the record update */
590     if (trps_validate_inforec(trps, rec) != TRP_SUCCESS) {
591       tr_notice("trps_handle_update: invalid record in TRP update.");
592       continue;
593     }
594
595     /* determine feasibility */
596     feas=trps_check_feasibility(trps, rec);
597     tr_debug("trps_handle_update: record feasibility=%d", feas);
598
599     /* do we have an existing route? */
600     route=trps_get_route(trps, trp_inforec_get_comm(rec), trp_inforec_get_realm(rec), trp_inforec_get_next_hop(rec));
601     if (route!=NULL) {
602       /* there was a route table entry already */
603       tr_debug("trps_handle_updates: route entry already exists.");
604       if (feas) {
605         /* Update is feasible. Accept it. */
606         trps_accept_update(trps, rec);
607       } else {
608         /* Update is infeasible. Ignore it unless the trust router has changed. */
609         if (0!=tr_name_cmp(trp_rentry_get_trust_router(route),
610                            trp_inforec_get_trust_router(rec))) {
611           /* the trust router associated with the route has changed, treat update as a retraction */
612           trps_retract_route(trps, route);
613         }
614       }
615     } else {
616       /* No existing route table entry. Ignore it unless it is feasible and not a retraction. */
617       tr_debug("trps_handle_update: no route entry exists yet.");
618       if (feas && trp_metric_is_finite(trp_inforec_get_metric(rec)))
619         trps_accept_update(trps, rec);
620     }
621   }
622   return TRP_SUCCESS;
623 }
624
625 /* choose the best route to comm/realm, optionally excluding routes to a particular peer */
626 static TRP_RENTRY *trps_find_best_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *exclude_peer)
627 {
628   TRP_RENTRY **entry=NULL;
629   TRP_RENTRY *best=NULL;
630   size_t n_entry=0;
631   unsigned int kk=0;
632   unsigned int kk_min=0;
633   unsigned int min_metric=TRP_METRIC_INFINITY;
634
635   entry=trp_rtable_get_realm_entries(trps->rtable, comm, realm, &n_entry);
636   for (kk=0; kk<n_entry; kk++) {
637     if (trp_rentry_get_metric(entry[kk]) < min_metric) {
638       if ((exclude_peer==NULL) || (0!=tr_name_cmp(trp_rentry_get_peer(entry[kk]),
639                                                   exclude_peer))) {
640         kk_min=kk;
641         min_metric=trp_rentry_get_metric(entry[kk]);
642       }
643     }
644   }
645   if (trp_metric_is_finite(min_metric));
646     best=entry[kk_min];
647   
648   talloc_free(entry);
649   return best;
650 }
651
652 /* TODO: think this through more carefully. At least ought to add hysteresis
653  * to avoid flapping between routers or routes. */
654 TRP_RC trps_update_active_routes(TRPS_INSTANCE *trps)
655 {
656   size_t n_apc=0, ii=0;
657   TR_NAME **apc=trp_rtable_get_apcs(trps->rtable, &n_apc);
658   size_t n_realm=0, jj=0;
659   TR_NAME **realm=NULL;
660   TRP_RENTRY *best_route=NULL, *cur_route=NULL;
661   unsigned int best_metric=0, cur_metric=0;
662
663   for (ii=0; ii<n_apc; ii++) {
664     realm=trp_rtable_get_apc_realms(trps->rtable, apc[ii], &n_realm);
665     for (jj=0; jj<n_realm; jj++) {
666       best_route=trps_find_best_route(trps, apc[ii], realm[jj], NULL);
667       if (best_route==NULL)
668         best_metric=TRP_METRIC_INFINITY;
669       else
670         best_metric=trp_rentry_get_metric(best_route);
671
672       cur_route=trps_get_selected_route(trps, apc[ii], realm[jj]);
673       if (cur_route!=NULL) {
674         cur_metric=trp_rentry_get_metric(cur_route);
675         if ((best_metric < cur_metric) && (trp_metric_is_finite(best_metric))) {
676           trp_rentry_set_selected(cur_route, 0);
677           trp_rentry_set_selected(best_route, 1);
678         } else if (!trp_metric_is_finite(cur_metric)) /* rejects infinite or invalid metrics */
679           trp_rentry_set_selected(cur_route, 0);
680       } else if (trp_metric_is_finite(best_metric))
681         trp_rentry_set_selected(best_route, 1);
682     }
683     if (realm!=NULL)
684       talloc_free(realm);
685     realm=NULL; n_realm=0;
686   }
687   if (apc!=NULL)
688     talloc_free(apc);
689   apc=NULL; n_apc=0;
690
691   return TRP_SUCCESS;
692 }
693
694 TRP_RC trps_handle_tr_msg(TRPS_INSTANCE *trps, TR_MSG *tr_msg)
695 {
696   TRP_RC rc=TRP_ERROR;
697
698   switch (tr_msg_get_msg_type(tr_msg)) {
699   case TRP_UPDATE:
700     rc=trps_handle_update(trps, tr_msg_get_trp_upd(tr_msg));
701     if (rc==TRP_SUCCESS) {
702       rc=trps_update_active_routes(trps);
703     }
704     return rc;
705
706   case TRP_REQUEST:
707     return TRP_UNSUPPORTED;
708
709   default:
710     /* unknown error or one we don't care about (e.g., TID messages) */
711     return TRP_ERROR;
712   }
713 }
714
715 /* true if curtime >= expiry */
716 static int trps_expired(struct timespec *expiry, struct timespec *curtime)
717 {
718   return ((curtime->tv_sec > expiry->tv_sec)
719          || ((curtime->tv_sec == expiry->tv_sec)
720             &&(curtime->tv_nsec > expiry->tv_nsec)));
721 }
722
723 /* Sweep for expired routes. For each expired route, if its metric is infinite, the route is flushed.
724  * If its metric is finite, the metric is set to infinite and the route's expiration time is updated. */
725 TRP_RC trps_sweep_routes(TRPS_INSTANCE *trps)
726 {
727   struct timespec sweep_time={0,0};
728   TRP_RENTRY **entry=NULL;
729   size_t n_entry=0;
730   size_t ii=0;
731
732   /* use a single time for the entire sweep */
733   if (0!=clock_gettime(CLOCK_REALTIME, &sweep_time)) {
734     tr_err("trps_sweep_routes: could not read realtime clock.");
735     sweep_time.tv_sec=0;
736     sweep_time.tv_nsec=0;
737     return TRP_ERROR;
738   }
739
740   entry=trp_rtable_get_entries(trps->rtable, &n_entry); /* must talloc_free *entry */
741
742   /* loop over the entries */
743   for (ii=0; ii<n_entry; ii++) {
744     if (trps_expired(trp_rentry_get_expiry(entry[ii]), &sweep_time)) {
745       tr_debug("trps_sweep_routes: route expired.");
746       if (!trp_metric_is_finite(trp_rentry_get_metric(entry[ii]))) {
747         /* flush route */
748         tr_debug("trps_sweep_routes: metric was infinity, flushing route.");
749         trp_rtable_remove(trps->rtable, entry[ii]); /* entry[ii] is no longer valid */
750         entry[ii]=NULL;
751       } else {
752         /* set metric to infinity and reset timer */
753         tr_debug("trps_sweep_routes: setting metric to infinity and resetting expiry.");
754         trp_rentry_set_metric(entry[ii], TRP_METRIC_INFINITY);
755         trp_rentry_set_expiry(entry[ii], trps_compute_expiry(trps,
756                                                              trp_rentry_get_interval(entry[ii]),
757                                                              trp_rentry_get_expiry(entry[ii])));
758       }
759     }
760   }
761
762   talloc_free(entry);
763   return TRP_SUCCESS;
764 }
765
766 /* select the correct route to comm/realm to be announced to peer */
767 static TRP_RENTRY *trps_select_realm_update(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer_gssname)
768 {
769   TRP_RENTRY *route;
770
771   /* Take the currently selected route unless it is through the peer we're sending the update to.
772    * I.e., enforce the split horizon rule. */
773   route=trp_rtable_get_selected_entry(trps->rtable, comm, realm);
774   if (route==NULL) {
775     /* No selected route, this should only happen if the only route has been retracted,
776      * in which case we do not want to advertise it. */
777     return NULL;
778   }
779   if (0==tr_name_cmp(peer_gssname, trp_rentry_get_peer(route))) {
780     /* the selected entry goes through the peer we're reporting to, choose an alternate */
781     route=trps_find_best_route(trps, comm, realm, peer_gssname);
782     if ((route==NULL) || (!trp_metric_is_finite(trp_rentry_get_metric(route))))
783       route=NULL; /* don't advertise a nonexistent or retracted route */
784   }
785   return route;
786 }
787
788 /* returns an array of pointers to updates (*not* an array of updates). Returns number of entries
789  * via n_update parameter. (The allocated space will generally be larger than required, see note in
790  * the code.) */
791 static TRP_RENTRY **trps_select_updates_for_peer(TALLOC_CTX *memctx, TRPS_INSTANCE *trps, TR_NAME *peer_gssname, size_t *n_update)
792 {
793   size_t n_apc=0;
794   TR_NAME **apc=trp_rtable_get_apcs(trps->rtable, &n_apc);
795   TR_NAME **realm=NULL;
796   size_t n_realm=0;
797   size_t ii=0, jj=0;
798   TRP_RENTRY *best=NULL;
799   TRP_RENTRY **result=NULL;
800   size_t n_used=0;
801
802   /* Need to allocate space for the results. For simplicity, we just allocate a block
803    * with space for every route table entry to be returned. This is guaranteed to be large
804    * enough. If the routing table gets very large, this may be wasteful, but that seems
805    * unlikely to be significant in the near future. */
806   result=talloc_array(memctx, TRP_RENTRY *, trp_rtable_size(trps->rtable));
807   if (result==NULL) {
808     talloc_free(apc);
809     *n_update=0;
810     return NULL;
811   }
812   
813   for (ii=0; ii<n_apc; ii++) {
814     realm=trp_rtable_get_apc_realms(trps->rtable, apc[ii], &n_realm);
815     for (jj=0; jj<n_realm; jj++) {
816       best=trps_select_realm_update(trps, apc[ii], realm[jj], peer_gssname);
817       if (best!=NULL)
818         result[n_used++]=best;
819     }
820     if (realm!=NULL)
821       talloc_free(realm);
822     realm=NULL;
823     n_realm=0;
824   }
825   if (apc!=NULL)
826     talloc_free(apc);
827
828   *n_update=n_used;
829   return result;
830 }
831
832 /* convert an rentry into a new trp update info record */
833 static TRP_INFOREC *trps_rentry_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_RENTRY *entry)
834 {
835   TRP_INFOREC *rec=trp_inforec_new(mem_ctx, TRP_INFOREC_TYPE_ROUTE);
836   unsigned int linkcost=0;
837
838   if (rec!=NULL) {
839     linkcost=trp_peer_get_linkcost(trps_get_peer(trps,
840                                                  trp_rentry_get_next_hop(entry)));
841
842     /* Note that we leave the next hop empty since the recipient fills that in.
843      * This is where we add the link cost (currently always 1) to the next peer. */
844     if ((trp_inforec_set_comm(rec, trp_rentry_dup_apc(entry)) != TRP_SUCCESS)
845        ||(trp_inforec_set_realm(rec, trp_rentry_dup_realm(entry)) != TRP_SUCCESS)
846        ||(trp_inforec_set_trust_router(rec, trp_rentry_dup_trust_router(entry)) != TRP_SUCCESS)
847        ||(trp_inforec_set_metric(rec, trp_rentry_get_metric(entry)+linkcost) != TRP_SUCCESS)
848        ||(trp_inforec_set_interval(rec, trps_get_update_interval(trps)) != TRP_SUCCESS)) {
849       tr_err("trps_rentry_to_inforec: error creating route update.");
850       talloc_free(rec);
851       rec=NULL;
852     }
853   }
854   return rec;
855 }
856
857 TRP_RC trps_scheduled_update(TRPS_INSTANCE *trps)
858 {
859   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
860   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
861   TRP_PEER *peer=NULL;
862   TR_MSG msg; /* not a pointer! */
863   TRP_UPD *upd=NULL;
864   TRP_RENTRY **update_list=NULL;
865   TRP_INFOREC *rec=NULL;
866   size_t n_updates=0, ii=0;
867   char *encoded=NULL;
868   TRP_RC rc=TRP_ERROR;
869   TR_NAME *peer_gssname=NULL;
870
871   if (iter==NULL) {
872     tr_err("trps_scheduled_update: failed to allocate peer table iterator.");
873     talloc_free(tmp_ctx);
874     return TRP_NOMEM;
875   }
876
877   for (peer=trp_ptable_iter_first(iter, trps->ptable);
878        peer!=NULL;
879        peer=trp_ptable_iter_next(iter))
880   {
881     peer_gssname=trp_peer_get_gssname(peer);
882     tr_debug("trps_scheduled_update: preparing scheduled route update for %.*s",
883              peer_gssname->len, peer_gssname->buf);
884     /* do not fill in peer, recipient does that */
885     update_list=trps_select_updates_for_peer(tmp_ctx, trps, peer_gssname, &n_updates);
886     tr_free_name(peer_gssname); peer_gssname=NULL;
887     if ((n_updates>0) && (update_list!=NULL)) {
888       tr_debug("trps_scheduled_update: sending %u update records.", (unsigned int)n_updates);
889       upd=trp_upd_new(tmp_ctx);
890
891       for (ii=0; ii<n_updates; ii++) {
892         rec=trps_rentry_to_inforec(tmp_ctx, trps, update_list[ii]);
893         if (rec==NULL) {
894           tr_err("trps_scheduled_update: could not create all update records.");
895           rc=TRP_ERROR;
896           goto cleanup;
897         }
898         trp_upd_add_inforec(upd, rec);
899       }
900       talloc_free(update_list);
901       update_list=NULL;
902
903       /* now encode the update message */
904       tr_msg_set_trp_upd(&msg, upd);
905       encoded=tr_msg_encode(&msg);
906       if (encoded==NULL) {
907         tr_err("trps_scheduled_update: error encoding update.");
908         rc=TRP_ERROR;
909         goto cleanup;
910       }
911
912       tr_debug("trps_scheduled_update: adding message to queue.");
913       if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
914         tr_err("trps_scheduled_update: error queueing update.");
915       else
916         tr_debug("trps_scheduled_update: update queued successfully.");
917
918       encoded=NULL;
919       tr_msg_free_encoded(encoded);
920       trp_upd_free(upd);
921       upd=NULL;
922     }
923   }
924   
925 cleanup:
926   trp_ptable_iter_free(iter);
927   talloc_free(tmp_ctx);
928   return rc;
929 }        
930
931 TRP_RC trps_add_route(TRPS_INSTANCE *trps, TRP_RENTRY *route)
932 {
933   trp_rtable_add(trps->rtable, route); /* should return status */
934   return TRP_SUCCESS; 
935 }
936
937 TRP_RC trps_add_peer(TRPS_INSTANCE *trps, TRP_PEER *peer)
938 {
939   return trp_ptable_add(trps->ptable, peer);
940 }
941
942 TRP_PEER *trps_get_peer(TRPS_INSTANCE *trps, TR_NAME *gssname)
943 {
944   return trp_ptable_find(trps->ptable, gssname);
945 }