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