Partial handling of incoming route requests.
[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 (upd==NULL) {
414     tr_notice("trps_validate_update: null TRP update.");
415     return TRP_BADARG;
416   }
417
418   if (trp_upd_get_inforec(upd)==NULL) {
419     tr_notice("trps_validate_update: received TRP update with no info records.");
420     return TRP_ERROR;
421   }
422
423   if (trp_upd_get_peer(upd)==NULL) {
424     tr_notice("trps_validate_update: received TRP update without origin peer information.");
425     return TRP_ERROR;
426   }
427   
428   return TRP_SUCCESS;
429 }
430
431 /* ensure that the update could be accepted if feasible */
432 static TRP_RC trps_validate_inforec(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
433 {
434   switch(trp_inforec_get_type(rec)) {
435   case TRP_INFOREC_TYPE_ROUTE:
436     if ((trp_inforec_get_comm(rec)==NULL)
437        || (trp_inforec_get_realm(rec)==NULL)
438        || (trp_inforec_get_trust_router(rec)==NULL)
439        || (trp_inforec_get_next_hop(rec)==NULL)) {
440       tr_debug("trps_validate_inforec: missing record info.");
441       return TRP_ERROR;
442     }
443
444     /* check for valid metric */
445     if (trp_metric_is_invalid(trp_inforec_get_metric(rec))) {
446       tr_debug("trps_validate_inforec: invalid metric (%u).", trp_inforec_get_metric(rec));
447       return TRP_ERROR;
448     }
449
450     /* check for valid interval */
451     if (trp_inforec_get_interval(rec)==TRP_INTERVAL_INVALID) {
452       tr_debug("trps_validate_inforec: invalid interval.");
453       return TRP_ERROR;
454     }
455     break;
456
457   default:
458     tr_notice("trps_validate_inforec: unsupported record type.");
459     return TRP_UNSUPPORTED;
460   }
461
462   return TRP_SUCCESS;
463 }
464
465 /* link cost to a peer */
466 static unsigned int trps_cost(TRPS_INSTANCE *trps, TR_NAME *peer)
467 {
468   return 1;
469 }
470
471 static unsigned int trps_advertised_metric(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
472 {
473   TRP_ROUTE *entry=trp_rtable_get_entry(trps->rtable, comm, realm, peer);
474   if (entry==NULL)
475     return TRP_METRIC_INFINITY;
476   return trp_route_get_metric(entry) + trps_cost(trps, peer);
477 }
478
479 static int trps_check_feasibility(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
480 {
481   unsigned int rec_metric=trp_inforec_get_metric(rec);
482   unsigned int new_metric=0;
483   unsigned int current_metric=0;
484   TR_NAME *next_hop=NULL;
485
486   /* we check these in the validation stage, but just in case... */
487   if (trp_metric_is_invalid(rec_metric))
488     return 0;
489
490   /* retractions (aka infinite metrics) are always feasible */
491   if (trp_metric_is_infinite(rec_metric))
492     return 1;
493
494   /* updates from our current next hop are always feasible*/
495   next_hop=trps_get_next_hop(trps,
496                              trp_inforec_get_comm(rec),
497                              trp_inforec_get_realm(rec));;
498   if ((next_hop!=NULL)
499      && (0==tr_name_cmp(next_hop,trp_inforec_get_next_hop(rec)))) {
500     return 1;
501   }
502     
503
504   /* compare the existing metric we advertise to what we would advertise
505    * if we accept this update */
506   current_metric=trps_advertised_metric(trps,
507                                         trp_inforec_get_comm(rec),
508                                         trp_inforec_get_realm(rec),
509                                         trp_inforec_get_next_hop(rec));
510   new_metric=rec_metric + trps_cost(trps, trp_inforec_get_next_hop(rec));
511   if (new_metric <= current_metric)
512     return 1;
513   else
514     return 0;
515 }
516
517 /* uses memory pointed to by *ts, also returns that value. On error, its contents are {0,0} */
518 static struct timespec *trps_compute_expiry(TRPS_INSTANCE *trps, unsigned int interval, struct timespec *ts)
519 {
520   const unsigned int small_factor=3; /* how many intervals we wait before expiring */
521   if (0!=clock_gettime(CLOCK_REALTIME, ts)) {
522     tr_err("trps_compute_expiry: could not read realtime clock.");
523     ts->tv_sec=0;
524     ts->tv_nsec=0;
525   }
526   ts->tv_sec += small_factor*interval;
527   return ts;
528 }
529
530 static TRP_RC trps_accept_update(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
531 {
532   TRP_ROUTE *entry=NULL;
533
534   entry=trp_rtable_get_entry(trps->rtable,
535                              trp_inforec_get_comm(rec),
536                              trp_inforec_get_realm(rec),
537                              trp_inforec_get_next_hop(rec));
538   if (entry==NULL) {
539     entry=trp_route_new(NULL);
540     if (entry==NULL) {
541       tr_err("trps_accept_update: unable to allocate new entry.");
542       return TRP_NOMEM;
543     }
544
545     trp_route_set_apc(entry, tr_dup_name(trp_inforec_get_comm(rec)));
546     trp_route_set_realm(entry, tr_dup_name(trp_inforec_get_realm(rec)));
547     trp_route_set_peer(entry, tr_dup_name(trp_inforec_get_next_hop(rec)));
548     trp_route_set_trust_router(entry, tr_dup_name(trp_inforec_get_trust_router(rec)));
549     trp_route_set_next_hop(entry, tr_dup_name(trp_inforec_get_next_hop(rec)));
550     if ((trp_route_get_apc(entry)==NULL)
551        ||(trp_route_get_realm(entry)==NULL)
552        ||(trp_route_get_peer(entry)==NULL)
553        ||(trp_route_get_trust_router(entry)==NULL)
554        ||(trp_route_get_next_hop(entry)==NULL)) {
555       /* at least one field could not be allocated */
556       tr_err("trps_accept_update: unable to allocate all fields for entry.");
557       trp_route_free(entry);
558       return TRP_NOMEM;
559     }
560     trp_rtable_add(trps->rtable, entry);
561   }
562
563   /* We now have an entry in the table, whether it's new or not. Update metric and expiry, unless
564    * the metric is infinity. An infinite metric can only occur here if we just retracted an existing
565    * route (we never accept retractions as new routes), so there is no risk of leaving the expiry
566    * time unset on a new route entry. */
567   tr_debug("trps_accept_update: accepting route update.");
568   trp_route_set_metric(entry, trp_inforec_get_metric(rec));
569   trp_route_set_interval(entry, trp_inforec_get_interval(rec));
570
571   /* check whether the trust router has changed */
572   if (0!=tr_name_cmp(trp_route_get_trust_router(entry),
573                      trp_inforec_get_trust_router(rec))) {
574     /* The name changed. Set this route as triggered. */
575     tr_debug("trps_accept_update: trust router for route changed.");
576     trp_route_set_triggered(entry, 1);
577     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec)); /* frees old name */
578   }
579   if (!trps_route_retracted(trps, entry)) {
580     tr_debug("trps_accept_update: route not retracted, setting expiry timer.");
581     trp_route_set_expiry(entry, trps_compute_expiry(trps,
582                                                      trp_route_get_interval(entry),
583                                                      trp_route_get_expiry(entry)));
584   }
585   return TRP_SUCCESS;
586 }
587
588 static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
589 {
590   unsigned int feas=0;
591   TRP_INFOREC *rec=NULL;
592   TRP_ROUTE *route=NULL;
593
594   if (trps_validate_update(trps, upd) != TRP_SUCCESS) {
595     tr_notice("trps_handle_update: received invalid TRP update.");
596     return TRP_ERROR;
597   }
598
599   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
600     /* validate/sanity check the record update */
601     if (trps_validate_inforec(trps, rec) != TRP_SUCCESS) {
602       tr_notice("trps_handle_update: invalid record in TRP update, discarding entire update.");
603       return TRP_ERROR;
604     }
605   }
606
607   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
608     /* determine feasibility */
609     feas=trps_check_feasibility(trps, rec);
610     tr_debug("trps_handle_update: record feasibility=%d", feas);
611
612     /* do we have an existing route? */
613     route=trps_get_route(trps,
614                          trp_inforec_get_comm(rec),
615                          trp_inforec_get_realm(rec),
616                          trp_inforec_get_next_hop(rec));
617     if (route!=NULL) {
618       /* there was a route table entry already */
619       tr_debug("trps_handle_updates: route entry already exists.");
620       if (feas) {
621         /* Update is feasible. Accept it. */
622         trps_accept_update(trps, rec);
623       } else {
624         /* Update is infeasible. Ignore it unless the trust router has changed. */
625         if (0!=tr_name_cmp(trp_route_get_trust_router(route),
626                            trp_inforec_get_trust_router(rec))) {
627           /* the trust router associated with the route has changed, treat update as a retraction */
628           trps_retract_route(trps, route);
629         }
630       }
631     } else {
632       /* No existing route table entry. Ignore it unless it is feasible and not a retraction. */
633       tr_debug("trps_handle_update: no route entry exists yet.");
634       if (feas && trp_metric_is_finite(trp_inforec_get_metric(rec)))
635         trps_accept_update(trps, rec);
636     }
637   }
638   return TRP_SUCCESS;
639 }
640
641 static TRP_RC trps_validate_request(TRPS_INSTANCE *trps, TRP_REQ *req)
642 {
643   if (req==NULL) {
644     tr_notice("trps_validate_request: null TRP request.");
645     return TRP_BADARG;
646   }
647
648   if (trp_req_get_comm(req)==NULL) {
649     tr_notice("trps_validate_request: received TRP request with null community.");
650     return TRP_ERROR;
651   }
652   
653   if (trp_req_get_realm(req)==NULL) {
654     tr_notice("trps_validate_request: received TRP request with null realm.");
655     return TRP_ERROR;
656   }
657   
658   if (trp_req_get_peer(req)==NULL) {
659     tr_notice("trps_validate_request: received TRP request without origin peer information.");
660     return TRP_ERROR;
661   }
662   
663   return TRP_SUCCESS;
664 }
665
666 /* choose the best route to comm/realm, optionally excluding routes to a particular peer */
667 static TRP_ROUTE *trps_find_best_route(TRPS_INSTANCE *trps,
668                                         TR_NAME *comm,
669                                         TR_NAME *realm,
670                                         TR_NAME *exclude_peer)
671 {
672   TRP_ROUTE **entry=NULL;
673   TRP_ROUTE *best=NULL;
674   size_t n_entry=0;
675   unsigned int kk=0;
676   unsigned int kk_min=0;
677   unsigned int min_metric=TRP_METRIC_INFINITY;
678
679   entry=trp_rtable_get_realm_entries(trps->rtable, comm, realm, &n_entry);
680   for (kk=0; kk<n_entry; kk++) {
681     if (trp_route_get_metric(entry[kk]) < min_metric) {
682       if ((exclude_peer==NULL) || (0!=tr_name_cmp(trp_route_get_peer(entry[kk]),
683                                                   exclude_peer))) {
684         kk_min=kk;
685         min_metric=trp_route_get_metric(entry[kk]);
686       } 
687     }
688   }
689   if (trp_metric_is_finite(min_metric))
690     best=entry[kk_min];
691   
692   talloc_free(entry);
693   return best;
694 }
695
696 /* TODO: think this through more carefully. At least ought to add hysteresis
697  * to avoid flapping between routers or routes. */
698 TRP_RC trps_update_active_routes(TRPS_INSTANCE *trps)
699 {
700   size_t n_apc=0, ii=0;
701   TR_NAME **apc=trp_rtable_get_apcs(trps->rtable, &n_apc);
702   size_t n_realm=0, jj=0;
703   TR_NAME **realm=NULL;
704   TRP_ROUTE *best_route=NULL, *cur_route=NULL;
705   unsigned int best_metric=0, cur_metric=0;
706
707   for (ii=0; ii<n_apc; ii++) {
708     realm=trp_rtable_get_apc_realms(trps->rtable, apc[ii], &n_realm);
709     for (jj=0; jj<n_realm; jj++) {
710       best_route=trps_find_best_route(trps, apc[ii], realm[jj], NULL);
711       if (best_route==NULL)
712         best_metric=TRP_METRIC_INFINITY;
713       else
714         best_metric=trp_route_get_metric(best_route);
715
716       cur_route=trps_get_selected_route(trps, apc[ii], realm[jj]);
717       if (cur_route!=NULL) {
718         cur_metric=trp_route_get_metric(cur_route);
719         if ((best_metric < cur_metric) && (trp_metric_is_finite(best_metric))) {
720           /* The new route has a lower metric than the previous, and is finite. Accept. */
721           trp_route_set_selected(cur_route, 0);
722           trp_route_set_selected(best_route, 1);
723         } else if (!trp_metric_is_finite(cur_metric)) /* rejects infinite or invalid metrics */
724           trp_route_set_selected(cur_route, 0);
725       } else if (trp_metric_is_finite(best_metric)) {
726         trp_route_set_selected(best_route, 1);
727       }
728     }
729     if (realm!=NULL)
730       talloc_free(realm);
731     realm=NULL; n_realm=0;
732   }
733   if (apc!=NULL)
734     talloc_free(apc);
735   apc=NULL; n_apc=0;
736
737   return TRP_SUCCESS;
738 }
739
740 /* true if curtime >= expiry */
741 static int trps_expired(struct timespec *expiry, struct timespec *curtime)
742 {
743   return ((curtime->tv_sec > expiry->tv_sec)
744          || ((curtime->tv_sec == expiry->tv_sec)
745             &&(curtime->tv_nsec > expiry->tv_nsec)));
746 }
747
748 /* Sweep for expired routes. For each expired route, if its metric is infinite, the route is flushed.
749  * If its metric is finite, the metric is set to infinite and the route's expiration time is updated. */
750 TRP_RC trps_sweep_routes(TRPS_INSTANCE *trps)
751 {
752   struct timespec sweep_time={0,0};
753   TRP_ROUTE **entry=NULL;
754   size_t n_entry=0;
755   size_t ii=0;
756
757   /* use a single time for the entire sweep */
758   if (0!=clock_gettime(CLOCK_REALTIME, &sweep_time)) {
759     tr_err("trps_sweep_routes: could not read realtime clock.");
760     sweep_time.tv_sec=0;
761     sweep_time.tv_nsec=0;
762     return TRP_ERROR;
763   }
764
765   entry=trp_rtable_get_entries(trps->rtable, &n_entry); /* must talloc_free *entry */
766
767   /* loop over the entries */
768   for (ii=0; ii<n_entry; ii++) {
769     if (!trp_route_is_local(entry[ii]) && trps_expired(trp_route_get_expiry(entry[ii]), &sweep_time)) {
770       tr_debug("trps_sweep_routes: route expired.");
771       if (!trp_metric_is_finite(trp_route_get_metric(entry[ii]))) {
772         /* flush route */
773         tr_debug("trps_sweep_routes: metric was infinity, flushing route.");
774         trp_rtable_remove(trps->rtable, entry[ii]); /* entry[ii] is no longer valid */
775         entry[ii]=NULL;
776       } else {
777         /* set metric to infinity and reset timer */
778         tr_debug("trps_sweep_routes: setting metric to infinity and resetting expiry.");
779         trp_route_set_metric(entry[ii], TRP_METRIC_INFINITY);
780         trp_route_set_expiry(entry[ii], trps_compute_expiry(trps,
781                                                              trp_route_get_interval(entry[ii]),
782                                                              trp_route_get_expiry(entry[ii])));
783       }
784     }
785   }
786
787   talloc_free(entry);
788   return TRP_SUCCESS;
789 }
790
791 /* select the correct route to comm/realm to be announced to peer */
792 static TRP_ROUTE *trps_select_realm_update(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer_gssname)
793 {
794   TRP_ROUTE *route;
795
796   /* Take the currently selected route unless it is through the peer we're sending the update to.
797    * I.e., enforce the split horizon rule. */
798   route=trp_rtable_get_selected_entry(trps->rtable, comm, realm);
799   if (route==NULL) {
800     /* No selected route, this should only happen if the only route has been retracted,
801      * in which case we do not want to advertise it. */
802     return NULL;
803   }
804   tr_debug("trps_select_realm_update: %s vs %s", peer_gssname->buf,
805            trp_route_get_peer(route)->buf);
806   if (0==tr_name_cmp(peer_gssname, trp_route_get_peer(route))) {
807     tr_debug("trps_select_realm_update: matched, finding alternate route");
808     /* the selected entry goes through the peer we're reporting to, choose an alternate */
809     route=trps_find_best_route(trps, comm, realm, peer_gssname);
810     if ((route==NULL) || (!trp_metric_is_finite(trp_route_get_metric(route))))
811       return NULL; /* don't advertise a nonexistent or retracted route */
812   }
813   return route;
814 }
815
816 /* returns an array of pointers to updates (*not* an array of updates). Returns number of entries
817  * via n_update parameter. (The allocated space will generally be larger than required, see note in
818  * the code.) If triggered is set, sends only triggered updates. */
819 static TRP_ROUTE **trps_select_updates_for_peer(TALLOC_CTX *memctx,
820                                                  TRPS_INSTANCE *trps,
821                                                  TR_NAME *peer_gssname,
822                                                  int triggered,
823                                                  size_t *n_update)
824 {
825   size_t n_apc=0;
826   TR_NAME **apc=trp_rtable_get_apcs(trps->rtable, &n_apc);
827   TR_NAME **realm=NULL;
828   size_t n_realm=0;
829   size_t ii=0, jj=0;
830   TRP_ROUTE *best=NULL;
831   TRP_ROUTE **result=NULL;
832   size_t n_used=0;
833
834   /* Need to allocate space for the results. For simplicity, we just allocate a block
835    * with space for every route table entry to be returned. This is guaranteed to be large
836    * enough. If the routing table gets very large, this may be wasteful, but that seems
837    * unlikely to be significant in the near future. */
838   result=talloc_array(memctx, TRP_ROUTE *, trp_rtable_size(trps->rtable));
839   if (result==NULL) {
840     talloc_free(apc);
841     *n_update=0;
842     return NULL;
843   }
844   
845   for (ii=0; ii<n_apc; ii++) {
846     realm=trp_rtable_get_apc_realms(trps->rtable, apc[ii], &n_realm);
847     for (jj=0; jj<n_realm; jj++) {
848       best=trps_select_realm_update(trps, apc[ii], realm[jj], peer_gssname);
849       /* If we found a route, add it to the list. If triggered!=0, then only
850        * add triggered routes. */
851       if ((best!=NULL) && ((!triggered) || trp_route_is_triggered(best)))
852         result[n_used++]=best;
853     }
854     if (realm!=NULL)
855       talloc_free(realm);
856     realm=NULL;
857     n_realm=0;
858   }
859   if (apc!=NULL)
860     talloc_free(apc);
861
862   *n_update=n_used;
863   return result;
864 }
865
866 /* add metrics */
867 static unsigned int trps_metric_add(unsigned int m1, unsigned int m2)
868 {
869   if (trp_metric_is_invalid(m1) || trp_metric_is_invalid(m2))
870     return TRP_METRIC_INVALID;
871
872   if (trp_metric_is_infinite(m1) || trp_metric_is_infinite(m2))
873     return TRP_METRIC_INFINITY;
874
875   if (trp_metric_is_finite(m1+m2))
876     return m1+m2;
877   else
878     return TRP_METRIC_INFINITY;
879 }
880
881 /* convert an rentry into a new trp update info record */
882 static TRP_INFOREC *trps_route_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
883 {
884   TRP_INFOREC *rec=trp_inforec_new(mem_ctx, TRP_INFOREC_TYPE_ROUTE);
885   unsigned int linkcost=0;
886
887   if (rec!=NULL) {
888     if (trp_route_is_local(route))
889       linkcost=0;
890     else {
891       linkcost=trp_peer_get_linkcost(trps_get_peer(trps,
892                                                    trp_route_get_next_hop(route)));
893     }
894
895     /* Note that we leave the next hop empty since the recipient fills that in.
896      * This is where we add the link cost (currently always 1) to the next peer. */
897     if ((trp_inforec_set_comm(rec, trp_route_dup_apc(route)) != TRP_SUCCESS)
898        ||(trp_inforec_set_realm(rec, trp_route_dup_realm(route)) != TRP_SUCCESS)
899        ||(trp_inforec_set_trust_router(rec, trp_route_dup_trust_router(route)) != TRP_SUCCESS)
900        ||(trp_inforec_set_metric(rec,
901                                  trps_metric_add(trp_route_get_metric(route),
902                                                  linkcost)) != TRP_SUCCESS)
903        ||(trp_inforec_set_interval(rec, trps_get_update_interval(trps)) != TRP_SUCCESS)) {
904       tr_err("trps_route_to_inforec: error creating route update.");
905       talloc_free(rec);
906       rec=NULL;
907     }
908   }
909   return rec;
910 }
911
912 /* all routes to a single peer, unless comm/realm are specified (both or neither must be NULL) */
913 static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
914                                    TR_NAME *peer_gssname,
915                                    TRP_UPDATE_TYPE update_type,
916                                    TR_NAME *comm,
917                                    TR_NAME *realm)
918 {
919   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
920   TR_MSG msg; /* not a pointer! */
921   TRP_UPD *upd=NULL;
922   TRP_ROUTE **update_list=NULL;
923   TRP_INFOREC *rec=NULL;
924   size_t n_updates=0, ii=0;
925   char *encoded=NULL;
926   TRP_RC rc=TRP_ERROR;
927   TRP_PEER *peer=trps_get_peer(trps, peer_gssname);
928
929   if (!trps_peer_connected(trps, peer)) {
930     tr_debug("trps_update_one_peer: no TRP connection to %.*s, skipping.",
931              peer_gssname->len, peer_gssname->buf);
932     goto cleanup;
933   }
934   if (update_type==TRP_UPDATE_TRIGGERED) {
935     tr_debug("trps_update_one_peer: preparing triggered route update for %.*s",
936              peer_gssname->len, peer_gssname->buf);
937   } else {
938     tr_debug("trps_update_one_peer: preparing scheduled route update for %.*s",
939              peer_gssname->len, peer_gssname->buf);
940   }
941   /* do not fill in peer, recipient does that */
942
943   if ((comm==NULL) && (realm==NULL)) {
944     /* do all realms */
945     update_list=trps_select_updates_for_peer(tmp_ctx,
946                                              trps,
947                                              peer_gssname,
948                                              update_type==TRP_UPDATE_TRIGGERED,
949                                             &n_updates);
950   } else if ((comm!=NULL) && (realm!=NULL)) {
951     /* a single community/realm was requested */
952     update_list=talloc(tmp_ctx, TRP_ROUTE *);
953     if (update_list==NULL) {
954       tr_err("trps_update_one_peer: could not allocate update_list.");
955       rc=TRP_NOMEM;
956       goto cleanup;
957     }
958     *update_list=trps_select_realm_update(trps, comm, realm, peer_gssname);
959     if (*update_list==NULL) {
960       /* no update to send */
961       rc=TRP_SUCCESS;
962       goto cleanup;
963     }
964     n_updates=1;
965   } else {
966     tr_err("trps_update_one_peer: error: only comm or realm was specified.");
967     rc=TRP_ERROR;
968     goto cleanup;
969   }
970   if ((n_updates>0) && (update_list!=NULL)) {
971     tr_debug("trps_update_one_peer: sending %u update records.", (unsigned int)n_updates);
972     upd=trp_upd_new(tmp_ctx);
973
974     for (ii=0; ii<n_updates; ii++) {
975       rec=trps_route_to_inforec(tmp_ctx, trps, update_list[ii]);
976       if (rec==NULL) {
977         tr_err("trps_update_one_peer: could not create all update records.");
978         rc=TRP_ERROR;
979         goto cleanup;
980       }
981       trp_upd_add_inforec(upd, rec);
982     }
983     talloc_free(update_list);
984     update_list=NULL;
985
986     /* now encode the update message */
987     tr_msg_set_trp_upd(&msg, upd);
988     encoded=tr_msg_encode(&msg);
989     if (encoded==NULL) {
990       tr_err("trps_update_one_peer: error encoding update.");
991       rc=TRP_ERROR;
992       goto cleanup;
993     }
994
995     tr_debug("trps_update_one_peer: adding message to queue.");
996     if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
997       tr_err("trps_update_one_peer: error queueing update.");
998     else
999       tr_debug("trps_update_one_peer: update queued successfully.");
1000
1001     encoded=NULL;
1002     tr_msg_free_encoded(encoded);
1003     trp_upd_free(upd);
1004     upd=NULL;
1005   }
1006
1007 cleanup:
1008   talloc_free(tmp_ctx);
1009   return rc;
1010 }
1011
1012 /* all routes to all peers */
1013 TRP_RC trps_update(TRPS_INSTANCE *trps, TRP_UPDATE_TYPE update_type)
1014 {
1015   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1016   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
1017   TRP_PEER *peer=NULL;
1018   TRP_RC rc=TRP_SUCCESS;
1019
1020   if (iter==NULL) {
1021     tr_err("trps_update: failed to allocate peer table iterator.");
1022     talloc_free(tmp_ctx);
1023     return TRP_NOMEM;
1024   }
1025
1026   for (peer=trp_ptable_iter_first(iter, trps->ptable);
1027        peer!=NULL && rc==TRP_SUCCESS;
1028        peer=trp_ptable_iter_next(iter))
1029   {
1030     rc=trps_update_one_peer(trps, trp_peer_get_gssname(peer), update_type, NULL, NULL);
1031   }
1032   
1033   trp_ptable_iter_free(iter);
1034   trp_rtable_clear_triggered(trps->rtable); /* don't re-send triggered updates */
1035   talloc_free(tmp_ctx);
1036   return rc;
1037 }        
1038
1039 TRP_RC trps_add_route(TRPS_INSTANCE *trps, TRP_ROUTE *route)
1040 {
1041   trp_rtable_add(trps->rtable, route); /* should return status */
1042   return TRP_SUCCESS; 
1043 }
1044
1045 /* steals the peer object */
1046 TRP_RC trps_add_peer(TRPS_INSTANCE *trps, TRP_PEER *peer)
1047 {
1048   return trp_ptable_add(trps->ptable, peer);
1049 }
1050
1051 TRP_PEER *trps_get_peer(TRPS_INSTANCE *trps, TR_NAME *gssname)
1052 {
1053   return trp_ptable_find(trps->ptable, gssname);
1054 }
1055
1056 int trps_peer_connected(TRPS_INSTANCE *trps, TRP_PEER *peer)
1057 {
1058   TRPC_INSTANCE *trpc=trps_find_trpc(trps, peer);
1059   if (trpc==NULL)
1060     return 0;
1061
1062   if (trpc_get_status(trpc)==TRP_CONNECTION_UP)
1063     return 1;
1064   else
1065     return 0;
1066 }
1067
1068
1069 static TRP_RC trps_handle_request(TRPS_INSTANCE *trps, TRP_REQ *req)
1070 {
1071   TR_NAME *comm=NULL;
1072   TR_NAME *realm=NULL;
1073
1074   tr_debug("trps_handle_request: handling TRP request.");
1075
1076   if (trps_validate_request(trps, req) != TRP_SUCCESS) {
1077     tr_notice("trps_handle_request: received invalid TRP request.");
1078     return TRP_ERROR;
1079   }
1080
1081   if (!trp_req_is_wildcard(req)) {
1082     comm=trp_req_get_comm(req);
1083     realm=trp_req_get_realm(req);
1084     tr_debug("trps_handle_request: route for %.*s/%.*s requested.",
1085              comm->len, comm->buf, realm->len, realm->buf);
1086   } else {
1087     tr_debug("trps_handle_request: all routes requested.");
1088   }
1089   return trps_update_one_peer(trps, trp_req_get_peer(req), TRP_UPDATE_REQUESTED, comm, realm);
1090 }
1091
1092
1093 TRP_RC trps_handle_tr_msg(TRPS_INSTANCE *trps, TR_MSG *tr_msg)
1094 {
1095   TRP_RC rc=TRP_ERROR;
1096
1097   switch (tr_msg_get_msg_type(tr_msg)) {
1098   case TRP_UPDATE:
1099     rc=trps_handle_update(trps, tr_msg_get_trp_upd(tr_msg));
1100     if (rc==TRP_SUCCESS) {
1101       rc=trps_update_active_routes(trps);
1102       trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
1103     }
1104     return rc;
1105
1106   case TRP_REQUEST:
1107     rc=trps_handle_request(trps, tr_msg_get_trp_req(tr_msg));
1108     return rc;
1109
1110   default:
1111     /* unknown error or one we don't care about (e.g., TID messages) */
1112     return TRP_ERROR;
1113   }
1114 }
1115