Fix memory freeing bugs. Seems stable, even through loss of connections.
[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   return cur;
144 }
145
146 void trps_add_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *new)
147 {
148   if (trps->conn==NULL)
149     trps->conn=new;
150   else
151     trp_connection_append(trps->conn, new);
152
153   talloc_steal(trps, new);
154 }
155
156 /* ok to call more than once; guarantees connection no longer in the list.
157  * Caller is responsible for freeing the removed element afterwards.  */
158 void trps_remove_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *remove)
159 {
160   trps->conn=trp_connection_remove(trps->conn, remove);
161 }
162
163 void trps_add_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *trpc)
164 {
165   if (trps->trpc==NULL)
166     trps->trpc=trpc;
167   else
168     trpc_append(trps->trpc, trpc);
169
170   talloc_steal(trps, trpc);
171 }
172
173 /* ok to call more than once; guarantees trpc no longer in the list.
174  * Caller is responsible for freeing the removed element afterwards.  */
175 void trps_remove_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *remove)
176 {
177   trps->trpc=trpc_remove(trps->trpc, remove);
178 }
179
180 TRP_RC trps_send_msg(TRPS_INSTANCE *trps, TRP_PEER *peer, const char *msg)
181 {
182   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
183   TR_MQ_MSG *mq_msg=NULL;
184   char *msg_dup=NULL;
185   TRP_RC rc=TRP_ERROR;
186   TRPC_INSTANCE *trpc=NULL;
187
188   /* get the connection for this peer */
189   trpc=trps_find_trpc(trps, peer);
190   if ((trpc==NULL) || (trpc_get_status(trps->trpc)!=TRP_CONNECTION_UP)) {
191     /* We could just let these sit on the queue in the hopes that a connection
192      * is eventually established. However, we'd then have to ensure the queue
193      * didn't keep growing, etc. */
194     tr_warning("trps_send_msg: skipping message queued while TRPC connection not up.");
195   } else {
196     mq_msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_SEND);
197     msg_dup=talloc_strdup(mq_msg, msg); /* get local copy in mq_msg context */
198     tr_mq_msg_set_payload(mq_msg, msg_dup, NULL); /* no need for a free() func */
199     trpc_mq_append(trpc, mq_msg);
200     rc=TRP_SUCCESS;
201   }
202   talloc_free(tmp_ctx);
203   return rc;
204 }
205
206 static int trps_listen (TRPS_INSTANCE *trps, int port) 
207 {
208   int rc = 0;
209   int conn = -1;
210   int optval = 1;
211
212   union {
213     struct sockaddr_storage storage;
214     struct sockaddr_in in4;
215   } addr;
216
217   struct sockaddr_in *saddr = (struct sockaddr_in *) &addr.in4;
218
219   saddr->sin_port = htons (port);
220   saddr->sin_family = AF_INET;
221   saddr->sin_addr.s_addr = INADDR_ANY;
222
223   if (0 > (conn = socket (AF_INET, SOCK_STREAM, 0)))
224     return conn;
225
226   setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
227
228   if (0 > (rc = bind (conn, (struct sockaddr *) saddr, sizeof(struct sockaddr_in))))
229     return rc;
230
231   if (0 > (rc = listen(conn, 512)))
232     return rc;
233
234   tr_debug("trps_listen: TRP Server listening on port %d", port);
235   return conn;
236 }
237
238 #if 0 /* remove this if I forget to do so */
239 /* returns EACCES if authorization is denied */
240 int trps_auth_cb(gss_name_t clientName, gss_buffer_t displayName, void *data)
241 {
242   TRPS_INSTANCE *trps = (TRPS_INSTANCE *)data;
243   int result=0;
244
245   if (0!=trps->auth_handler(clientName, displayName, trps->cookie)) {
246     tr_debug("trps_auth_cb: client '%.*s' denied authorization.", displayName->length, displayName->value);
247     result=EACCES; /* denied */
248   }
249
250   return result;
251 }
252 #endif 
253
254 /* get the currently selected route if available */
255 TRP_ROUTE *trps_get_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
256 {
257   return trp_rtable_get_entry(trps->rtable, comm, realm, peer);
258 }
259
260 TRP_ROUTE *trps_get_selected_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
261 {
262   return trp_rtable_get_selected_entry(trps->rtable, comm, realm);
263 }
264
265 /* copy the result if you want to keep it */
266 TR_NAME *trps_get_next_hop(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
267 {
268   TRP_ROUTE *route=trps_get_selected_route(trps, comm, realm);
269   if (route==NULL)
270     return NULL;
271
272   return trp_route_get_next_hop(route);
273 }
274
275
276 /* mark a route as retracted */
277 static void trps_retract_route(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
278 {
279   trp_route_set_metric(entry, TRP_METRIC_INFINITY);
280   trp_route_set_triggered(entry, 1);
281 }
282
283 /* is this route retracted? */
284 static int trps_route_retracted(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
285 {
286   return (trp_metric_is_infinite(trp_route_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   TR_MSG *msg=NULL;
381   TRP_RC rc=TRP_ERROR;
382
383   /* try to establish a GSS context */
384   if (0!=trp_connection_auth(conn, trps->auth_handler, trps->cookie)) {
385     tr_notice("tr_trps_conn_thread: failed to authorize connection");
386     trp_connection_close(conn);
387   } else {
388     tr_notice("trps_handle_connection: authorized connection");
389   
390     /* loop as long as the connection exists */
391     while (trp_connection_get_status(conn)==TRP_CONNECTION_UP) {
392       rc=trps_read_message(trps, conn, &msg);
393       switch(rc) {
394       case TRP_SUCCESS:
395         trps->msg_handler(trps, conn, msg); /* send the TR_MSG off to the callback */
396         break;
397
398       case TRP_ERROR:
399         trp_connection_close(conn);
400         break;
401
402       default:
403         tr_debug("trps_handle_connection: trps_read_message failed (%d)", rc);
404       }
405     }
406
407     tr_debug("trps_handle_connection: connection closed.");
408   }
409 }
410
411 static TRP_RC trps_validate_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
412 {
413   if (trp_upd_get_inforec(upd)==NULL) {
414     tr_notice("trps_validate_update: received TRP update with no info records.");
415     return TRP_ERROR;
416   }
417
418   if (trp_upd_get_peer(upd)==NULL) {
419     tr_notice("trps_validate_update: received TRP update without origin peer information.");
420     return TRP_ERROR;
421   }
422   
423   return TRP_SUCCESS;
424 }
425
426 /* ensure that the update could be accepted if feasible */
427 static TRP_RC trps_validate_inforec(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
428 {
429   switch(trp_inforec_get_type(rec)) {
430   case TRP_INFOREC_TYPE_ROUTE:
431     if ((trp_inforec_get_comm(rec)==NULL)
432        || (trp_inforec_get_realm(rec)==NULL)
433        || (trp_inforec_get_trust_router(rec)==NULL)
434        || (trp_inforec_get_next_hop(rec)==NULL)) {
435       tr_debug("trps_validate_inforec: missing record info.");
436       return TRP_ERROR;
437     }
438
439     /* check for valid metric */
440     if (trp_metric_is_invalid(trp_inforec_get_metric(rec))) {
441       tr_debug("trps_validate_inforec: invalid metric (%u).", trp_inforec_get_metric(rec));
442       return TRP_ERROR;
443     }
444
445     /* check for valid interval */
446     if (trp_inforec_get_interval(rec)==TRP_INTERVAL_INVALID) {
447       tr_debug("trps_validate_inforec: invalid interval.");
448       return TRP_ERROR;
449     }
450     break;
451
452   default:
453     tr_notice("trps_validate_inforec: unsupported record type.");
454     return TRP_UNSUPPORTED;
455   }
456
457   return TRP_SUCCESS;
458 }
459
460 /* link cost to a peer */
461 static unsigned int trps_cost(TRPS_INSTANCE *trps, TR_NAME *peer)
462 {
463   return 1;
464 }
465
466 static unsigned int trps_advertised_metric(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
467 {
468   TRP_ROUTE *entry=trp_rtable_get_entry(trps->rtable, comm, realm, peer);
469   if (entry==NULL)
470     return TRP_METRIC_INFINITY;
471   return trp_route_get_metric(entry) + trps_cost(trps, peer);
472 }
473
474 static int trps_check_feasibility(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
475 {
476   unsigned int rec_metric=trp_inforec_get_metric(rec);
477   unsigned int new_metric=0;
478   unsigned int current_metric=0;
479   TR_NAME *next_hop=NULL;
480
481   /* we check these in the validation stage, but just in case... */
482   if (trp_metric_is_invalid(rec_metric))
483     return 0;
484
485   /* retractions (aka infinite metrics) are always feasible */
486   if (trp_metric_is_infinite(rec_metric))
487     return 1;
488
489   /* updates from our current next hop are always feasible*/
490   next_hop=trps_get_next_hop(trps,
491                              trp_inforec_get_comm(rec),
492                              trp_inforec_get_realm(rec));;
493   if ((next_hop!=NULL)
494      && (0==tr_name_cmp(next_hop,trp_inforec_get_next_hop(rec)))) {
495     return 1;
496   }
497     
498
499   /* compare the existing metric we advertise to what we would advertise
500    * if we accept this update */
501   current_metric=trps_advertised_metric(trps,
502                                         trp_inforec_get_comm(rec),
503                                         trp_inforec_get_realm(rec),
504                                         trp_inforec_get_next_hop(rec));
505   new_metric=rec_metric + trps_cost(trps, trp_inforec_get_next_hop(rec));
506   if (new_metric <= current_metric)
507     return 1;
508   else
509     return 0;
510 }
511
512 /* uses memory pointed to by *ts, also returns that value. On error, its contents are {0,0} */
513 static struct timespec *trps_compute_expiry(TRPS_INSTANCE *trps, unsigned int interval, struct timespec *ts)
514 {
515   const unsigned int small_factor=3; /* how many intervals we wait before expiring */
516   if (0!=clock_gettime(CLOCK_REALTIME, ts)) {
517     tr_err("trps_compute_expiry: could not read realtime clock.");
518     ts->tv_sec=0;
519     ts->tv_nsec=0;
520   }
521   ts->tv_sec += small_factor*interval;
522   return ts;
523 }
524
525 static TRP_RC trps_accept_update(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
526 {
527   TRP_ROUTE *entry=NULL;
528
529   entry=trp_rtable_get_entry(trps->rtable,
530                              trp_inforec_get_comm(rec),
531                              trp_inforec_get_realm(rec),
532                              trp_inforec_get_next_hop(rec));
533   if (entry==NULL) {
534     entry=trp_route_new(NULL);
535     if (entry==NULL) {
536       tr_err("trps_accept_update: unable to allocate new entry.");
537       return TRP_NOMEM;
538     }
539
540     trp_route_set_apc(entry, tr_dup_name(trp_inforec_get_comm(rec)));
541     trp_route_set_realm(entry, tr_dup_name(trp_inforec_get_realm(rec)));
542     trp_route_set_peer(entry, tr_dup_name(trp_inforec_get_next_hop(rec)));
543     trp_route_set_trust_router(entry, tr_dup_name(trp_inforec_get_trust_router(rec)));
544     trp_route_set_next_hop(entry, tr_dup_name(trp_inforec_get_next_hop(rec)));
545     if ((trp_route_get_apc(entry)==NULL)
546        ||(trp_route_get_realm(entry)==NULL)
547        ||(trp_route_get_peer(entry)==NULL)
548        ||(trp_route_get_trust_router(entry)==NULL)
549        ||(trp_route_get_next_hop(entry)==NULL)) {
550       /* at least one field could not be allocated */
551       tr_err("trps_accept_update: unable to allocate all fields for entry.");
552       trp_route_free(entry);
553       return TRP_NOMEM;
554     }
555     trp_rtable_add(trps->rtable, entry);
556   }
557
558   /* We now have an entry in the table, whether it's new or not. Update metric and expiry, unless
559    * the metric is infinity. An infinite metric can only occur here if we just retracted an existing
560    * route (we never accept retractions as new routes), so there is no risk of leaving the expiry
561    * time unset on a new route entry. */
562   tr_debug("trps_accept_update: accepting route update.");
563   trp_route_set_metric(entry, trp_inforec_get_metric(rec));
564   trp_route_set_interval(entry, trp_inforec_get_interval(rec));
565
566   /* check whether the trust router has changed */
567   if (0!=tr_name_cmp(trp_route_get_trust_router(entry),
568                      trp_inforec_get_trust_router(rec))) {
569     /* The name changed. Set this route as triggered. */
570     tr_debug("trps_accept_update: trust router for route changed.");
571     trp_route_set_triggered(entry, 1);
572     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec)); /* frees old name */
573   }
574   if (!trps_route_retracted(trps, entry)) {
575     tr_debug("trps_accept_update: route not retracted, setting expiry timer.");
576     trp_route_set_expiry(entry, trps_compute_expiry(trps,
577                                                      trp_route_get_interval(entry),
578                                                      trp_route_get_expiry(entry)));
579   }
580   return TRP_SUCCESS;
581 }
582
583 /* TODO: handle community updates */
584 static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
585 {
586   unsigned int feas=0;
587   TRP_INFOREC *rec=NULL;
588   TRP_ROUTE *route=NULL;
589
590   if (trps_validate_update(trps, upd) != TRP_SUCCESS) {
591     tr_notice("trps_handle_update: received invalid TRP update.");
592     return TRP_ERROR;
593   }
594
595   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
596     /* validate/sanity check the record update */
597     if (trps_validate_inforec(trps, rec) != TRP_SUCCESS) {
598       tr_notice("trps_handle_update: invalid record in TRP update.");
599       continue;
600     }
601
602     /* determine feasibility */
603     feas=trps_check_feasibility(trps, rec);
604     tr_debug("trps_handle_update: record feasibility=%d", feas);
605
606     /* do we have an existing route? */
607     route=trps_get_route(trps,
608                          trp_inforec_get_comm(rec),
609                          trp_inforec_get_realm(rec),
610                          trp_inforec_get_next_hop(rec));
611     if (route!=NULL) {
612       /* there was a route table entry already */
613       tr_debug("trps_handle_updates: route entry already exists.");
614       if (feas) {
615         /* Update is feasible. Accept it. */
616         trps_accept_update(trps, rec);
617       } else {
618         /* Update is infeasible. Ignore it unless the trust router has changed. */
619         if (0!=tr_name_cmp(trp_route_get_trust_router(route),
620                            trp_inforec_get_trust_router(rec))) {
621           /* the trust router associated with the route has changed, treat update as a retraction */
622           trps_retract_route(trps, route);
623         }
624       }
625     } else {
626       /* No existing route table entry. Ignore it unless it is feasible and not a retraction. */
627       tr_debug("trps_handle_update: no route entry exists yet.");
628       if (feas && trp_metric_is_finite(trp_inforec_get_metric(rec)))
629         trps_accept_update(trps, rec);
630     }
631   }
632   return TRP_SUCCESS;
633 }
634
635 /* choose the best route to comm/realm, optionally excluding routes to a particular peer */
636 static TRP_ROUTE *trps_find_best_route(TRPS_INSTANCE *trps,
637                                         TR_NAME *comm,
638                                         TR_NAME *realm,
639                                         TR_NAME *exclude_peer)
640 {
641   TRP_ROUTE **entry=NULL;
642   TRP_ROUTE *best=NULL;
643   size_t n_entry=0;
644   unsigned int kk=0;
645   unsigned int kk_min=0;
646   unsigned int min_metric=TRP_METRIC_INFINITY;
647
648   entry=trp_rtable_get_realm_entries(trps->rtable, comm, realm, &n_entry);
649   for (kk=0; kk<n_entry; kk++) {
650     if (trp_route_get_metric(entry[kk]) < min_metric) {
651       if ((exclude_peer==NULL) || (0!=tr_name_cmp(trp_route_get_peer(entry[kk]),
652                                                   exclude_peer))) {
653         kk_min=kk;
654         min_metric=trp_route_get_metric(entry[kk]);
655       } 
656     }
657   }
658   if (trp_metric_is_finite(min_metric))
659     best=entry[kk_min];
660   
661   talloc_free(entry);
662   return best;
663 }
664
665 /* TODO: think this through more carefully. At least ought to add hysteresis
666  * to avoid flapping between routers or routes. */
667 TRP_RC trps_update_active_routes(TRPS_INSTANCE *trps)
668 {
669   size_t n_apc=0, ii=0;
670   TR_NAME **apc=trp_rtable_get_apcs(trps->rtable, &n_apc);
671   size_t n_realm=0, jj=0;
672   TR_NAME **realm=NULL;
673   TRP_ROUTE *best_route=NULL, *cur_route=NULL;
674   unsigned int best_metric=0, cur_metric=0;
675
676   for (ii=0; ii<n_apc; ii++) {
677     realm=trp_rtable_get_apc_realms(trps->rtable, apc[ii], &n_realm);
678     for (jj=0; jj<n_realm; jj++) {
679       best_route=trps_find_best_route(trps, apc[ii], realm[jj], NULL);
680       if (best_route==NULL)
681         best_metric=TRP_METRIC_INFINITY;
682       else
683         best_metric=trp_route_get_metric(best_route);
684
685       cur_route=trps_get_selected_route(trps, apc[ii], realm[jj]);
686       if (cur_route!=NULL) {
687         cur_metric=trp_route_get_metric(cur_route);
688         if ((best_metric < cur_metric) && (trp_metric_is_finite(best_metric))) {
689           /* The new route has a lower metric than the previous, and is finite. Accept. */
690           trp_route_set_selected(cur_route, 0);
691           trp_route_set_selected(best_route, 1);
692         } else if (!trp_metric_is_finite(cur_metric)) /* rejects infinite or invalid metrics */
693           trp_route_set_selected(cur_route, 0);
694       } else if (trp_metric_is_finite(best_metric)) {
695         trp_route_set_selected(best_route, 1);
696       }
697     }
698     if (realm!=NULL)
699       talloc_free(realm);
700     realm=NULL; n_realm=0;
701   }
702   if (apc!=NULL)
703     talloc_free(apc);
704   apc=NULL; n_apc=0;
705
706   return TRP_SUCCESS;
707 }
708
709 TRP_RC trps_handle_tr_msg(TRPS_INSTANCE *trps, TR_MSG *tr_msg)
710 {
711   TRP_RC rc=TRP_ERROR;
712
713   switch (tr_msg_get_msg_type(tr_msg)) {
714   case TRP_UPDATE:
715     rc=trps_handle_update(trps, tr_msg_get_trp_upd(tr_msg));
716     if (rc==TRP_SUCCESS) {
717       rc=trps_update_active_routes(trps);
718       trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
719     }
720     return rc;
721
722   case TRP_REQUEST:
723     return TRP_UNSUPPORTED;
724
725   default:
726     /* unknown error or one we don't care about (e.g., TID messages) */
727     return TRP_ERROR;
728   }
729 }
730
731 /* true if curtime >= expiry */
732 static int trps_expired(struct timespec *expiry, struct timespec *curtime)
733 {
734   return ((curtime->tv_sec > expiry->tv_sec)
735          || ((curtime->tv_sec == expiry->tv_sec)
736             &&(curtime->tv_nsec > expiry->tv_nsec)));
737 }
738
739 /* Sweep for expired routes. For each expired route, if its metric is infinite, the route is flushed.
740  * If its metric is finite, the metric is set to infinite and the route's expiration time is updated. */
741 TRP_RC trps_sweep_routes(TRPS_INSTANCE *trps)
742 {
743   struct timespec sweep_time={0,0};
744   TRP_ROUTE **entry=NULL;
745   size_t n_entry=0;
746   size_t ii=0;
747
748   /* use a single time for the entire sweep */
749   if (0!=clock_gettime(CLOCK_REALTIME, &sweep_time)) {
750     tr_err("trps_sweep_routes: could not read realtime clock.");
751     sweep_time.tv_sec=0;
752     sweep_time.tv_nsec=0;
753     return TRP_ERROR;
754   }
755
756   entry=trp_rtable_get_entries(trps->rtable, &n_entry); /* must talloc_free *entry */
757
758   /* loop over the entries */
759   for (ii=0; ii<n_entry; ii++) {
760     if (!trp_route_is_local(entry[ii]) && trps_expired(trp_route_get_expiry(entry[ii]), &sweep_time)) {
761       tr_debug("trps_sweep_routes: route expired.");
762       if (!trp_metric_is_finite(trp_route_get_metric(entry[ii]))) {
763         /* flush route */
764         tr_debug("trps_sweep_routes: metric was infinity, flushing route.");
765         trp_rtable_remove(trps->rtable, entry[ii]); /* entry[ii] is no longer valid */
766         entry[ii]=NULL;
767       } else {
768         /* set metric to infinity and reset timer */
769         tr_debug("trps_sweep_routes: setting metric to infinity and resetting expiry.");
770         trp_route_set_metric(entry[ii], TRP_METRIC_INFINITY);
771         trp_route_set_expiry(entry[ii], trps_compute_expiry(trps,
772                                                              trp_route_get_interval(entry[ii]),
773                                                              trp_route_get_expiry(entry[ii])));
774       }
775     }
776   }
777
778   talloc_free(entry);
779   return TRP_SUCCESS;
780 }
781
782 /* select the correct route to comm/realm to be announced to peer */
783 static TRP_ROUTE *trps_select_realm_update(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer_gssname)
784 {
785   TRP_ROUTE *route;
786
787   /* Take the currently selected route unless it is through the peer we're sending the update to.
788    * I.e., enforce the split horizon rule. */
789   route=trp_rtable_get_selected_entry(trps->rtable, comm, realm);
790   if (route==NULL) {
791     /* No selected route, this should only happen if the only route has been retracted,
792      * in which case we do not want to advertise it. */
793     return NULL;
794   }
795   tr_debug("trps_select_realm_update: %s vs %s", peer_gssname->buf,
796            trp_route_get_peer(route)->buf);
797   if (0==tr_name_cmp(peer_gssname, trp_route_get_peer(route))) {
798     tr_debug("trps_select_realm_update: matched, finding alternate route");
799     /* the selected entry goes through the peer we're reporting to, choose an alternate */
800     route=trps_find_best_route(trps, comm, realm, peer_gssname);
801     if ((route==NULL) || (!trp_metric_is_finite(trp_route_get_metric(route))))
802       return NULL; /* don't advertise a nonexistent or retracted route */
803   }
804   return route;
805 }
806
807 /* returns an array of pointers to updates (*not* an array of updates). Returns number of entries
808  * via n_update parameter. (The allocated space will generally be larger than required, see note in
809  * the code.) If triggered is set, sends only triggered updates. */
810 static TRP_ROUTE **trps_select_updates_for_peer(TALLOC_CTX *memctx,
811                                                  TRPS_INSTANCE *trps,
812                                                  TR_NAME *peer_gssname,
813                                                  int triggered,
814                                                  size_t *n_update)
815 {
816   size_t n_apc=0;
817   TR_NAME **apc=trp_rtable_get_apcs(trps->rtable, &n_apc);
818   TR_NAME **realm=NULL;
819   size_t n_realm=0;
820   size_t ii=0, jj=0;
821   TRP_ROUTE *best=NULL;
822   TRP_ROUTE **result=NULL;
823   size_t n_used=0;
824
825   /* Need to allocate space for the results. For simplicity, we just allocate a block
826    * with space for every route table entry to be returned. This is guaranteed to be large
827    * enough. If the routing table gets very large, this may be wasteful, but that seems
828    * unlikely to be significant in the near future. */
829   result=talloc_array(memctx, TRP_ROUTE *, trp_rtable_size(trps->rtable));
830   if (result==NULL) {
831     talloc_free(apc);
832     *n_update=0;
833     return NULL;
834   }
835   
836   for (ii=0; ii<n_apc; ii++) {
837     realm=trp_rtable_get_apc_realms(trps->rtable, apc[ii], &n_realm);
838     for (jj=0; jj<n_realm; jj++) {
839       best=trps_select_realm_update(trps, apc[ii], realm[jj], peer_gssname);
840       /* If we found a route, add it to the list. If triggered!=0, then only
841        * add triggered routes. */
842       if ((best!=NULL) && ((!triggered) || trp_route_is_triggered(best)))
843         result[n_used++]=best;
844     }
845     if (realm!=NULL)
846       talloc_free(realm);
847     realm=NULL;
848     n_realm=0;
849   }
850   if (apc!=NULL)
851     talloc_free(apc);
852
853   *n_update=n_used;
854   return result;
855 }
856
857 /* add metrics */
858 static unsigned int trps_metric_add(unsigned int m1, unsigned int m2)
859 {
860   if (trp_metric_is_invalid(m1) || trp_metric_is_invalid(m2))
861     return TRP_METRIC_INVALID;
862
863   if (trp_metric_is_infinite(m1) || trp_metric_is_infinite(m2))
864     return TRP_METRIC_INFINITY;
865
866   if (trp_metric_is_finite(m1+m2))
867     return m1+m2;
868   else
869     return TRP_METRIC_INFINITY;
870 }
871
872 /* convert an rentry into a new trp update info record */
873 static TRP_INFOREC *trps_route_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
874 {
875   TRP_INFOREC *rec=trp_inforec_new(mem_ctx, TRP_INFOREC_TYPE_ROUTE);
876   unsigned int linkcost=0;
877
878   if (rec!=NULL) {
879     if (trp_route_is_local(route))
880       linkcost=0;
881     else {
882       linkcost=trp_peer_get_linkcost(trps_get_peer(trps,
883                                                    trp_route_get_next_hop(route)));
884     }
885
886     /* Note that we leave the next hop empty since the recipient fills that in.
887      * This is where we add the link cost (currently always 1) to the next peer. */
888     if ((trp_inforec_set_comm(rec, trp_route_dup_apc(route)) != TRP_SUCCESS)
889        ||(trp_inforec_set_realm(rec, trp_route_dup_realm(route)) != TRP_SUCCESS)
890        ||(trp_inforec_set_trust_router(rec, trp_route_dup_trust_router(route)) != TRP_SUCCESS)
891        ||(trp_inforec_set_metric(rec,
892                                  trps_metric_add(trp_route_get_metric(route),
893                                                  linkcost)) != TRP_SUCCESS)
894        ||(trp_inforec_set_interval(rec, trps_get_update_interval(trps)) != TRP_SUCCESS)) {
895       tr_err("trps_route_to_inforec: error creating route update.");
896       talloc_free(rec);
897       rec=NULL;
898     }
899   }
900   return rec;
901 }
902
903 TRP_RC trps_update(TRPS_INSTANCE *trps, TRP_UPDATE_TYPE triggered)
904 {
905   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
906   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
907   TRP_PEER *peer=NULL;
908   TR_MSG msg; /* not a pointer! */
909   TRP_UPD *upd=NULL;
910   TRP_ROUTE **update_list=NULL;
911   TRP_INFOREC *rec=NULL;
912   size_t n_updates=0, ii=0;
913   char *encoded=NULL;
914   TRP_RC rc=TRP_ERROR;
915   TR_NAME *peer_gssname=NULL;
916
917   if (iter==NULL) {
918     tr_err("trps_update: failed to allocate peer table iterator.");
919     talloc_free(tmp_ctx);
920     return TRP_NOMEM;
921   }
922
923   for (peer=trp_ptable_iter_first(iter, trps->ptable);
924        peer!=NULL;
925        peer=trp_ptable_iter_next(iter))
926   {
927     peer_gssname=trp_peer_get_gssname(peer);
928     if (!trps_peer_connected(trps, peer)) {
929       tr_debug("trps_update: no TRP connection to %.*s, skipping.",
930                peer_gssname->len, peer_gssname->buf);
931       continue;
932     }
933     if (triggered==TRP_UPDATE_TRIGGERED) {
934       tr_debug("trps_update: preparing triggered route update for %.*s",
935                peer_gssname->len, peer_gssname->buf);
936     } else {
937       tr_debug("trps_update: preparing scheduled route update for %.*s",
938                peer_gssname->len, peer_gssname->buf);
939     }
940     /* do not fill in peer, recipient does that */
941     update_list=trps_select_updates_for_peer(tmp_ctx,
942                                              trps,
943                                              peer_gssname,
944                                              triggered==TRP_UPDATE_TRIGGERED,
945                                             &n_updates);
946     if ((n_updates>0) && (update_list!=NULL)) {
947       tr_debug("trps_update: sending %u update records.", (unsigned int)n_updates);
948       upd=trp_upd_new(tmp_ctx);
949
950       for (ii=0; ii<n_updates; ii++) {
951         rec=trps_route_to_inforec(tmp_ctx, trps, update_list[ii]);
952         if (rec==NULL) {
953           tr_err("trps_update: could not create all update records.");
954           rc=TRP_ERROR;
955           goto cleanup;
956         }
957         trp_upd_add_inforec(upd, rec);
958       }
959       talloc_free(update_list);
960       update_list=NULL;
961
962       /* now encode the update message */
963       tr_msg_set_trp_upd(&msg, upd);
964       encoded=tr_msg_encode(&msg);
965       if (encoded==NULL) {
966         tr_err("trps_update: error encoding update.");
967         rc=TRP_ERROR;
968         goto cleanup;
969       }
970
971       tr_debug("trps_update: adding message to queue.");
972       if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
973         tr_err("trps_update: error queueing update.");
974       else
975         tr_debug("trps_update: update queued successfully.");
976
977       encoded=NULL;
978       tr_msg_free_encoded(encoded);
979       trp_upd_free(upd);
980       upd=NULL;
981     }
982   }
983   
984 cleanup:
985   trp_ptable_iter_free(iter);
986   trp_rtable_clear_triggered(trps->rtable); /* don't re-send triggered updates */
987   talloc_free(tmp_ctx);
988   return rc;
989 }        
990
991 TRP_RC trps_add_route(TRPS_INSTANCE *trps, TRP_ROUTE *route)
992 {
993   trp_rtable_add(trps->rtable, route); /* should return status */
994   return TRP_SUCCESS; 
995 }
996
997 /* steals the peer object */
998 TRP_RC trps_add_peer(TRPS_INSTANCE *trps, TRP_PEER *peer)
999 {
1000   return trp_ptable_add(trps->ptable, peer);
1001 }
1002
1003 TRP_PEER *trps_get_peer(TRPS_INSTANCE *trps, TR_NAME *gssname)
1004 {
1005   return trp_ptable_find(trps->ptable, gssname);
1006 }
1007
1008 int trps_peer_connected(TRPS_INSTANCE *trps, TRP_PEER *peer)
1009 {
1010   TRPC_INSTANCE *trpc=trps_find_trpc(trps, peer);
1011   if (trpc==NULL)
1012     return 0;
1013
1014   if (trpc_get_status(trpc)==TRP_CONNECTION_UP)
1015     return 1;
1016   else
1017     return 0;
1018 }