Bug fixes to make TID forwarding work between trust routers.
[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 <tr_gss.h>
12 #include <trp_ptable.h>
13 #include <trp_rtable.h>
14 #include <tr_debug.h>
15
16
17 static int trps_destructor(void *object)
18 {
19   TRPS_INSTANCE *trps=talloc_get_type_abort(object, TRPS_INSTANCE);
20   if (trps->rtable!=NULL)
21     trp_rtable_free(trps->rtable);
22   return 0;
23 }
24
25 TRPS_INSTANCE *trps_new (TALLOC_CTX *mem_ctx)
26 {
27   TRPS_INSTANCE *trps=talloc(mem_ctx, TRPS_INSTANCE);
28   if (trps!=NULL)  {
29     trps->hostname=NULL;
30     trps->port=0;
31     trps->cookie=NULL;
32     trps->conn=NULL;
33     trps->trpc=NULL;
34     trps->update_interval=(struct timeval){0,0};
35     trps->sweep_interval=(struct timeval){0,0};
36     trps->ptable=NULL;
37
38     trps->mq=tr_mq_new(trps);
39     if (trps->mq==NULL) {
40       /* failed to allocate mq */
41       talloc_free(trps);
42       return NULL;
43     }
44
45     trps->rtable=NULL;
46     if (trps_init_rtable(trps) != TRP_SUCCESS) {
47       /* failed to allocate rtable */
48       talloc_free(trps);
49       return NULL;
50     }
51
52     talloc_set_destructor((void *)trps, trps_destructor);
53   }
54   return trps;
55 }
56
57 /* create a new route table, first discarding an old one if necessary */
58 TRP_RC trps_init_rtable(TRPS_INSTANCE *trps)
59 {
60   if (trps->rtable != NULL) {
61     trp_rtable_free(trps->rtable);
62     trps->rtable=NULL;
63   }
64
65   trps->rtable=trp_rtable_new();
66   if (trps->rtable==NULL) {
67     return TRP_NOMEM;
68   }
69   return TRP_SUCCESS;
70 }
71
72 void trps_clear_rtable(TRPS_INSTANCE *trps)
73 {
74   trp_rtable_clear(trps->rtable);
75 }
76
77 void trps_free (TRPS_INSTANCE *trps)
78 {
79   if (trps!=NULL)
80     talloc_free(trps);
81 }
82
83 TR_MQ_MSG *trps_mq_pop(TRPS_INSTANCE *trps)
84 {
85   return tr_mq_pop(trps->mq);
86 }
87
88 void trps_mq_add(TRPS_INSTANCE *trps, TR_MQ_MSG *msg)
89 {
90   tr_mq_add(trps->mq, msg);
91 }
92
93 unsigned int trps_get_connect_interval(TRPS_INSTANCE *trps)
94 {
95   return trps->connect_interval.tv_sec;
96 }
97
98 void trps_set_connect_interval(TRPS_INSTANCE *trps, unsigned int interval)
99 {
100   trps->connect_interval.tv_sec=interval;
101   trps->connect_interval.tv_usec=0;
102 }
103
104 unsigned int trps_get_update_interval(TRPS_INSTANCE *trps)
105 {
106   return trps->update_interval.tv_sec;
107 }
108
109 void trps_set_update_interval(TRPS_INSTANCE *trps, unsigned int interval)
110 {
111   trps->update_interval.tv_sec=interval;
112   trps->update_interval.tv_usec=0;
113 }
114
115 unsigned int trps_get_sweep_interval(TRPS_INSTANCE *trps)
116 {
117   return trps->sweep_interval.tv_sec;
118 }
119
120 void trps_set_sweep_interval(TRPS_INSTANCE *trps, unsigned int interval)
121 {
122   trps->sweep_interval.tv_sec=interval;
123   trps->sweep_interval.tv_usec=0;
124 }
125
126 void trps_set_ptable(TRPS_INSTANCE *trps, TRP_PTABLE *ptable)
127 {
128   if (trps->ptable!=NULL)
129     trp_ptable_free(trps->ptable);
130   trps->ptable=ptable;
131 }
132
133 TRPC_INSTANCE *trps_find_trpc(TRPS_INSTANCE *trps, TRP_PEER *peer)
134 {
135   TRPC_INSTANCE *cur=NULL;
136   TR_NAME *name=NULL;
137   TR_NAME *peer_servicename=trp_peer_get_servicename(peer);
138
139   for (cur=trps->trpc; cur!=NULL; cur=trpc_get_next(cur)) {
140     name=trpc_get_gssname(cur);
141     if ((name!=NULL) && (0==tr_name_cmp(peer_servicename, name))) {
142       break;
143     }
144   }
145   return cur;
146 }
147
148 void trps_add_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *new)
149 {
150   if (trps->conn==NULL)
151     trps->conn=new;
152   else
153     trp_connection_append(trps->conn, new);
154
155   talloc_steal(trps, new);
156 }
157
158 /* ok to call more than once; guarantees connection no longer in the list.
159  * Caller is responsible for freeing the removed element afterwards.  */
160 void trps_remove_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *remove)
161 {
162   trps->conn=trp_connection_remove(trps->conn, remove);
163 }
164
165 void trps_add_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *trpc)
166 {
167   if (trps->trpc==NULL)
168     trps->trpc=trpc;
169   else
170     trpc_append(trps->trpc, trpc);
171
172   talloc_steal(trps, trpc);
173 }
174
175 /* ok to call more than once; guarantees trpc no longer in the list.
176  * Caller is responsible for freeing the removed element afterwards.  */
177 void trps_remove_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *remove)
178 {
179   trps->trpc=trpc_remove(trps->trpc, remove);
180 }
181
182 TRP_RC trps_send_msg(TRPS_INSTANCE *trps, TRP_PEER *peer, const char *msg)
183 {
184   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
185   TR_MQ_MSG *mq_msg=NULL;
186   char *msg_dup=NULL;
187   TRP_RC rc=TRP_ERROR;
188   TRPC_INSTANCE *trpc=NULL;
189
190   /* get the connection for this peer */
191   trpc=trps_find_trpc(trps, peer);
192   /* instead, let's let that happen and then clear the queue when an attempt to
193    * connect fails */
194   if (trpc==NULL) {
195     tr_warning("trps_send_msg: skipping message queued for missing TRP client entry.");
196   } else {
197     mq_msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_SEND, TR_MQ_PRIO_NORMAL);
198     msg_dup=talloc_strdup(mq_msg, msg); /* get local copy in mq_msg context */
199     tr_mq_msg_set_payload(mq_msg, msg_dup, NULL); /* no need for a free() func */
200     trpc_mq_add(trpc, mq_msg);
201     rc=TRP_SUCCESS;
202   }
203   talloc_free(tmp_ctx);
204   return rc;
205 }
206
207 static int trps_listen (TRPS_INSTANCE *trps, int port) 
208 {
209   int rc = 0;
210   int conn = -1;
211   int optval = 1;
212
213   union {
214     struct sockaddr_storage storage;
215     struct sockaddr_in in4;
216   } addr;
217
218   struct sockaddr_in *saddr = (struct sockaddr_in *) &addr.in4;
219
220   saddr->sin_port = htons (port);
221   saddr->sin_family = AF_INET;
222   saddr->sin_addr.s_addr = INADDR_ANY;
223
224   if (0 > (conn = socket (AF_INET, SOCK_STREAM, 0)))
225     return conn;
226
227   setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
228
229   if (0 > (rc = bind (conn, (struct sockaddr *) saddr, sizeof(struct sockaddr_in))))
230     return rc;
231
232   if (0 > (rc = listen(conn, 512)))
233     return rc;
234
235   tr_debug("trps_listen: TRP Server listening on port %d", port);
236   return conn;
237 }
238
239 /* get the currently selected route if available */
240 TRP_ROUTE *trps_get_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
241 {
242   return trp_rtable_get_entry(trps->rtable, comm, realm, peer);
243 }
244
245 TRP_ROUTE *trps_get_selected_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
246 {
247   tr_debug("trps_get_selected_route: entered. trps=%p, comm=%p, realm=%p", trps, comm, realm);
248   return trp_rtable_get_selected_entry(trps->rtable, comm, realm);
249 }
250
251 /* copy the result if you want to keep it */
252 TR_NAME *trps_get_next_hop(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
253 {
254   TRP_ROUTE *route=trps_get_selected_route(trps, comm, realm);
255   if (route==NULL)
256     return NULL;
257
258   return trp_route_get_next_hop(route);
259 }
260
261
262 /* mark a route as retracted */
263 static void trps_retract_route(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
264 {
265   trp_route_set_metric(entry, TRP_METRIC_INFINITY);
266   trp_route_set_triggered(entry, 1);
267 }
268
269 /* is this route retracted? */
270 static int trps_route_retracted(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
271 {
272   return (trp_metric_is_infinite(trp_route_get_metric(entry)));
273 }
274
275 static TRP_RC trps_read_message(TRPS_INSTANCE *trps, TRP_CONNECTION *conn, TR_MSG **msg)
276 {
277   int err=0;
278   char *buf=NULL;
279   size_t buflen = 0;
280   TRP_PEER *peer=NULL; /* entry in the peer table */
281   TR_NAME *conn_peer=NULL; /* name from the TRP_CONN, which comes from the gss context */
282
283   tr_debug("trps_read_message: started");
284   if (err = gsscon_read_encrypted_token(trp_connection_get_fd(conn),
285                                        *(trp_connection_get_gssctx(conn)), 
286                                        &buf,
287                                        &buflen)) {
288     tr_debug("trps_read_message: error");
289     if (buf)
290       free(buf);
291     return TRP_ERROR;
292   }
293
294   tr_debug("trps_read_message: message received, %u bytes.", (unsigned) buflen);
295   tr_debug("trps_read_message: %.*s", buflen, buf);
296
297   *msg=tr_msg_decode(buf, buflen);
298   free(buf);
299   if (*msg==NULL)
300     return TRP_NOPARSE;
301
302   conn_peer=trp_connection_get_peer(conn);
303   if (conn_peer==NULL) {
304     tr_err("trps_read_message: connection has no peer name");
305     return TRP_ERROR;
306   }
307
308   peer=trps_get_peer_by_gssname(trps, conn_peer);
309   if (peer==NULL) {
310     tr_err("trps_read_message: could not find peer with gssname=%s", trp_connection_get_gssname(conn));
311     return TRP_ERROR;
312   }
313
314   /* verify we received a message we support, otherwise drop it now */
315   switch (tr_msg_get_msg_type(*msg)) {
316   case TRP_UPDATE:
317     trp_upd_set_peer(tr_msg_get_trp_upd(*msg), tr_dup_name(conn_peer));
318     trp_upd_set_next_hop(tr_msg_get_trp_upd(*msg), trp_peer_get_server(peer), 0); /* TODO: 0 should be the configured TID port */
319     break;
320
321   case TRP_REQUEST:
322     trp_req_set_peer(tr_msg_get_trp_req(*msg), tr_dup_name(conn_peer));
323     break;
324
325   default:
326     tr_debug("trps_read_message: received unsupported message from %.*s", conn_peer->len, conn_peer->buf);
327     tr_msg_free_decoded(*msg);
328     *msg=NULL;
329     return TRP_UNSUPPORTED;
330   }
331   
332   return TRP_SUCCESS;
333 }
334
335 int trps_get_listener(TRPS_INSTANCE *trps,
336                       TRPS_MSG_FUNC msg_handler,
337                       TRP_AUTH_FUNC auth_handler,
338                       const char *hostname,
339                       unsigned int port,
340                       void *cookie)
341 {
342   int listen = -1;
343
344   if (0 > (listen = trps_listen(trps, port))) {
345     char errbuf[256];
346     if (0 == strerror_r(errno, errbuf, 256)) {
347       tr_debug("trps_get_listener: Error opening port %d: %s.", port, errbuf);
348     } else {
349       tr_debug("trps_get_listener: Unknown error openining port %d.", port);
350     }
351   } 
352
353   if (listen > 0) {
354     /* opening port succeeded */
355     tr_debug("trps_get_listener: Opened port %d.", port);
356     
357     /* make this socket non-blocking */
358     if (0 != fcntl(listen, F_SETFL, O_NONBLOCK)) {
359       tr_debug("trps_get_listener: Error setting O_NONBLOCK.");
360       close(listen);
361       listen=-1;
362     }
363   }
364
365   if (listen > 0) {
366     /* store the caller's request handler & cookie */
367     trps->msg_handler = msg_handler;
368     trps->auth_handler = auth_handler;
369     trps->hostname = talloc_strdup(trps, hostname);
370     trps->port = port;
371     trps->cookie = cookie;
372   }
373
374   return listen;
375 }
376
377 TRP_RC trps_authorize_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
378 {
379   /* try to establish a GSS context */
380   if (0!=trp_connection_auth(conn, trps->auth_handler, trps->cookie)) {
381     tr_notice("trps_authorize_connection: failed to authorize connection");
382     trp_connection_close(conn);
383     return TRP_ERROR;
384   }
385   tr_notice("trps_authorize_connection: authorized connection");
386   return TRP_SUCCESS;
387 }
388
389 void trps_handle_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
390 {
391   TR_MSG *msg=NULL;
392   TRP_RC rc=TRP_ERROR;
393
394   /* loop as long as the connection exists */
395   while (trp_connection_get_status(conn)==TRP_CONNECTION_UP) {
396     rc=trps_read_message(trps, conn, &msg);
397     switch(rc) {
398     case TRP_SUCCESS:
399       trps->msg_handler(trps, conn, msg); /* send the TR_MSG off to the callback */
400       break;
401
402     case TRP_ERROR:
403       trp_connection_close(conn);
404       break;
405
406     default:
407       tr_debug("trps_handle_connection: trps_read_message failed (%d)", rc);
408     }
409   }
410
411   tr_debug("trps_handle_connection: connection closed.");
412 }
413
414 static TRP_RC trps_validate_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
415 {
416   if (upd==NULL) {
417     tr_notice("trps_validate_update: null TRP update.");
418     return TRP_BADARG;
419   }
420
421   if (trp_upd_get_inforec(upd)==NULL) {
422     tr_notice("trps_validate_update: received TRP update with no info records.");
423     return TRP_ERROR;
424   }
425
426   if (trp_upd_get_peer(upd)==NULL) {
427     tr_notice("trps_validate_update: received TRP update without origin peer information.");
428     return TRP_ERROR;
429   }
430   
431   return TRP_SUCCESS;
432 }
433
434 /* ensure that the update could be accepted if feasible */
435 static TRP_RC trps_validate_inforec(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
436 {
437   switch(trp_inforec_get_type(rec)) {
438   case TRP_INFOREC_TYPE_ROUTE:
439     if ((trp_inforec_get_comm(rec)==NULL)
440        || (trp_inforec_get_realm(rec)==NULL)
441        || (trp_inforec_get_trust_router(rec)==NULL)
442        || (trp_inforec_get_next_hop(rec)==NULL)) {
443       tr_debug("trps_validate_inforec: missing record info.");
444       return TRP_ERROR;
445     }
446
447     /* check for valid metric */
448     if (trp_metric_is_invalid(trp_inforec_get_metric(rec))) {
449       tr_debug("trps_validate_inforec: invalid metric (%u).", trp_inforec_get_metric(rec));
450       return TRP_ERROR;
451     }
452
453     /* check for valid interval */
454     if (trp_inforec_get_interval(rec)==TRP_INTERVAL_INVALID) {
455       tr_debug("trps_validate_inforec: invalid interval.");
456       return TRP_ERROR;
457     }
458     break;
459
460   default:
461     tr_notice("trps_validate_inforec: unsupported record type.");
462     return TRP_UNSUPPORTED;
463   }
464
465   return TRP_SUCCESS;
466 }
467
468 /* link cost to a peer */
469 static unsigned int trps_cost(TRPS_INSTANCE *trps, TR_NAME *peer)
470 {
471   return 1;
472 }
473
474 static unsigned int trps_advertised_metric(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
475 {
476   TRP_ROUTE *entry=trp_rtable_get_entry(trps->rtable, comm, realm, peer);
477   if (entry==NULL)
478     return TRP_METRIC_INFINITY;
479   return trp_route_get_metric(entry) + trps_cost(trps, peer);
480 }
481
482 static int trps_check_feasibility(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
483 {
484   unsigned int rec_metric=trp_inforec_get_metric(rec);
485   unsigned int new_metric=0;
486   unsigned int current_metric=0;
487   TR_NAME *next_hop=NULL;
488
489   /* we check these in the validation stage, but just in case... */
490   if (trp_metric_is_invalid(rec_metric))
491     return 0;
492
493   /* retractions (aka infinite metrics) are always feasible */
494   if (trp_metric_is_infinite(rec_metric))
495     return 1;
496
497   /* updates from our current next hop are always feasible*/
498   next_hop=trps_get_next_hop(trps,
499                              trp_inforec_get_comm(rec),
500                              trp_inforec_get_realm(rec));;
501   if ((next_hop!=NULL)
502      && (0==tr_name_cmp(next_hop,trp_inforec_get_next_hop(rec)))) {
503     return 1;
504   }
505     
506
507   /* compare the existing metric we advertise to what we would advertise
508    * if we accept this update */
509   current_metric=trps_advertised_metric(trps,
510                                         trp_inforec_get_comm(rec),
511                                         trp_inforec_get_realm(rec),
512                                         trp_inforec_get_next_hop(rec));
513   new_metric=rec_metric + trps_cost(trps, trp_inforec_get_next_hop(rec));
514   if (new_metric <= current_metric)
515     return 1;
516   else
517     return 0;
518 }
519
520 /* uses memory pointed to by *ts, also returns that value. On error, its contents are {0,0} */
521 static struct timespec *trps_compute_expiry(TRPS_INSTANCE *trps, unsigned int interval, struct timespec *ts)
522 {
523   const unsigned int small_factor=3; /* how many intervals we wait before expiring */
524   if (0!=clock_gettime(CLOCK_REALTIME, ts)) {
525     tr_err("trps_compute_expiry: could not read realtime clock.");
526     ts->tv_sec=0;
527     ts->tv_nsec=0;
528   }
529   ts->tv_sec += small_factor*interval;
530   return ts;
531 }
532
533 static TRP_RC trps_accept_update(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
534 {
535   TRP_ROUTE *entry=NULL;
536
537   entry=trp_rtable_get_entry(trps->rtable,
538                              trp_inforec_get_comm(rec),
539                              trp_inforec_get_realm(rec),
540                              trp_inforec_get_next_hop(rec));
541   if (entry==NULL) {
542     entry=trp_route_new(NULL);
543     if (entry==NULL) {
544       tr_err("trps_accept_update: unable to allocate new entry.");
545       return TRP_NOMEM;
546     }
547
548     trp_route_set_comm(entry, trp_inforec_dup_comm(rec));
549     trp_route_set_realm(entry, trp_inforec_dup_realm(rec));
550     trp_route_set_peer(entry, trp_upd_dup_peer(upd));
551     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec));
552     trp_route_set_next_hop(entry, trp_inforec_dup_next_hop(rec));
553     /* TODO: pass next hop port (now defaults to TID_PORT) --jlr */
554     if ((trp_route_get_comm(entry)==NULL)
555        ||(trp_route_get_realm(entry)==NULL)
556        ||(trp_route_get_peer(entry)==NULL)
557        ||(trp_route_get_trust_router(entry)==NULL)
558        ||(trp_route_get_next_hop(entry)==NULL)) {
559       /* at least one field could not be allocated */
560       tr_err("trps_accept_update: unable to allocate all fields for entry.");
561       trp_route_free(entry);
562       return TRP_NOMEM;
563     }
564     trp_rtable_add(trps->rtable, entry);
565   }
566
567   /* We now have an entry in the table, whether it's new or not. Update metric and expiry, unless
568    * the metric is infinity. An infinite metric can only occur here if we just retracted an existing
569    * route (we never accept retractions as new routes), so there is no risk of leaving the expiry
570    * time unset on a new route entry. */
571   tr_debug("trps_accept_update: accepting route update.");
572   trp_route_set_metric(entry, trp_inforec_get_metric(rec));
573   trp_route_set_interval(entry, trp_inforec_get_interval(rec));
574
575   /* check whether the trust router has changed */
576   if (0!=tr_name_cmp(trp_route_get_trust_router(entry),
577                      trp_inforec_get_trust_router(rec))) {
578     /* The name changed. Set this route as triggered. */
579     tr_debug("trps_accept_update: trust router for route changed.");
580     trp_route_set_triggered(entry, 1);
581     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec)); /* frees old name */
582   }
583   if (!trps_route_retracted(trps, entry)) {
584     tr_debug("trps_accept_update: route not retracted, setting expiry timer.");
585     trp_route_set_expiry(entry, trps_compute_expiry(trps,
586                                                      trp_route_get_interval(entry),
587                                                      trp_route_get_expiry(entry)));
588   }
589   return TRP_SUCCESS;
590 }
591
592 static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
593 {
594   unsigned int feas=0;
595   TRP_INFOREC *rec=NULL;
596   TRP_ROUTE *route=NULL;
597
598   if (trps_validate_update(trps, upd) != TRP_SUCCESS) {
599     tr_notice("trps_handle_update: received invalid TRP update.");
600     return TRP_ERROR;
601   }
602
603   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
604     /* validate/sanity check the record update */
605     if (trps_validate_inforec(trps, rec) != TRP_SUCCESS) {
606       tr_notice("trps_handle_update: invalid record in TRP update, discarding entire update.");
607       return TRP_ERROR;
608     }
609   }
610
611   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
612     /* determine feasibility */
613     feas=trps_check_feasibility(trps, rec);
614     tr_debug("trps_handle_update: record feasibility=%d", feas);
615
616     /* do we have an existing route? */
617     route=trps_get_route(trps,
618                          trp_inforec_get_comm(rec),
619                          trp_inforec_get_realm(rec),
620                          trp_upd_get_peer(upd));
621     if (route!=NULL) {
622       /* there was a route table entry already */
623       tr_debug("trps_handle_updates: route entry already exists.");
624       if (feas) {
625         /* Update is feasible. Accept it. */
626         trps_accept_update(trps, upd, rec);
627       } else {
628         /* Update is infeasible. Ignore it unless the trust router has changed. */
629         if (0!=tr_name_cmp(trp_route_get_trust_router(route),
630                            trp_inforec_get_trust_router(rec))) {
631           /* the trust router associated with the route has changed, treat update as a retraction */
632           trps_retract_route(trps, route);
633         }
634       }
635     } else {
636       /* No existing route table entry. Ignore it unless it is feasible and not a retraction. */
637       tr_debug("trps_handle_update: no route entry exists yet.");
638       if (feas && trp_metric_is_finite(trp_inforec_get_metric(rec)))
639         trps_accept_update(trps, upd, rec);
640     }
641   }
642   return TRP_SUCCESS;
643 }
644
645 static TRP_RC trps_validate_request(TRPS_INSTANCE *trps, TRP_REQ *req)
646 {
647   if (req==NULL) {
648     tr_notice("trps_validate_request: null TRP request.");
649     return TRP_BADARG;
650   }
651
652   if (trp_req_get_comm(req)==NULL) {
653     tr_notice("trps_validate_request: received TRP request with null community.");
654     return TRP_ERROR;
655   }
656   
657   if (trp_req_get_realm(req)==NULL) {
658     tr_notice("trps_validate_request: received TRP request with null realm.");
659     return TRP_ERROR;
660   }
661   
662   if (trp_req_get_peer(req)==NULL) {
663     tr_notice("trps_validate_request: received TRP request without origin peer information.");
664     return TRP_ERROR;
665   }
666   
667   return TRP_SUCCESS;
668 }
669
670 /* choose the best route to comm/realm, optionally excluding routes to a particular peer */
671 static TRP_ROUTE *trps_find_best_route(TRPS_INSTANCE *trps,
672                                         TR_NAME *comm,
673                                         TR_NAME *realm,
674                                         TR_NAME *exclude_peer)
675 {
676   TRP_ROUTE **entry=NULL;
677   TRP_ROUTE *best=NULL;
678   size_t n_entry=0;
679   unsigned int kk=0;
680   unsigned int kk_min=0;
681   unsigned int min_metric=TRP_METRIC_INFINITY;
682
683   entry=trp_rtable_get_realm_entries(trps->rtable, comm, realm, &n_entry);
684   for (kk=0; kk<n_entry; kk++) {
685     if (trp_route_get_metric(entry[kk]) < min_metric) {
686       if ((exclude_peer==NULL) || (0!=tr_name_cmp(trp_route_get_peer(entry[kk]),
687                                                   exclude_peer))) {
688         kk_min=kk;
689         min_metric=trp_route_get_metric(entry[kk]);
690       } 
691     }
692   }
693   if (trp_metric_is_finite(min_metric))
694     best=entry[kk_min];
695   
696   talloc_free(entry);
697   return best;
698 }
699
700 /* TODO: think this through more carefully. At least ought to add hysteresis
701  * to avoid flapping between routers or routes. */
702 TRP_RC trps_update_active_routes(TRPS_INSTANCE *trps)
703 {
704   size_t n_comm=0, ii=0;
705   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
706   size_t n_realm=0, jj=0;
707   TR_NAME **realm=NULL;
708   TRP_ROUTE *best_route=NULL, *cur_route=NULL;
709   unsigned int best_metric=0, cur_metric=0;
710
711   for (ii=0; ii<n_comm; ii++) {
712     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
713     for (jj=0; jj<n_realm; jj++) {
714       best_route=trps_find_best_route(trps, comm[ii], realm[jj], NULL);
715       if (best_route==NULL)
716         best_metric=TRP_METRIC_INFINITY;
717       else
718         best_metric=trp_route_get_metric(best_route);
719
720       cur_route=trps_get_selected_route(trps, comm[ii], realm[jj]);
721       if (cur_route!=NULL) {
722         cur_metric=trp_route_get_metric(cur_route);
723         if ((best_metric < cur_metric) && (trp_metric_is_finite(best_metric))) {
724           /* The new route has a lower metric than the previous, and is finite. Accept. */
725           trp_route_set_selected(cur_route, 0);
726           trp_route_set_selected(best_route, 1);
727         } else if (!trp_metric_is_finite(cur_metric)) /* rejects infinite or invalid metrics */
728           trp_route_set_selected(cur_route, 0);
729       } else if (trp_metric_is_finite(best_metric)) {
730         trp_route_set_selected(best_route, 1);
731       }
732     }
733     if (realm!=NULL)
734       talloc_free(realm);
735     realm=NULL; n_realm=0;
736   }
737   if (comm!=NULL)
738     talloc_free(comm);
739   comm=NULL; n_comm=0;
740
741   return TRP_SUCCESS;
742 }
743
744 /* true if curtime >= expiry */
745 static int trps_expired(struct timespec *expiry, struct timespec *curtime)
746 {
747   return ((curtime->tv_sec > expiry->tv_sec)
748          || ((curtime->tv_sec == expiry->tv_sec)
749             &&(curtime->tv_nsec > expiry->tv_nsec)));
750 }
751
752 /* Sweep for expired routes. For each expired route, if its metric is infinite, the route is flushed.
753  * If its metric is finite, the metric is set to infinite and the route's expiration time is updated. */
754 TRP_RC trps_sweep_routes(TRPS_INSTANCE *trps)
755 {
756   struct timespec sweep_time={0,0};
757   TRP_ROUTE **entry=NULL;
758   size_t n_entry=0;
759   size_t ii=0;
760
761   /* use a single time for the entire sweep */
762   if (0!=clock_gettime(CLOCK_REALTIME, &sweep_time)) {
763     tr_err("trps_sweep_routes: could not read realtime clock.");
764     sweep_time.tv_sec=0;
765     sweep_time.tv_nsec=0;
766     return TRP_ERROR;
767   }
768
769   entry=trp_rtable_get_entries(trps->rtable, &n_entry); /* must talloc_free *entry */
770
771   /* loop over the entries */
772   for (ii=0; ii<n_entry; ii++) {
773     if (!trp_route_is_local(entry[ii]) && trps_expired(trp_route_get_expiry(entry[ii]), &sweep_time)) {
774       tr_debug("trps_sweep_routes: route expired.");
775       if (!trp_metric_is_finite(trp_route_get_metric(entry[ii]))) {
776         /* flush route */
777         tr_debug("trps_sweep_routes: metric was infinity, flushing route.");
778         trp_rtable_remove(trps->rtable, entry[ii]); /* entry[ii] is no longer valid */
779         entry[ii]=NULL;
780       } else {
781         /* set metric to infinity and reset timer */
782         tr_debug("trps_sweep_routes: setting metric to infinity and resetting expiry.");
783         trp_route_set_metric(entry[ii], TRP_METRIC_INFINITY);
784         trp_route_set_expiry(entry[ii], trps_compute_expiry(trps,
785                                                              trp_route_get_interval(entry[ii]),
786                                                              trp_route_get_expiry(entry[ii])));
787       }
788     }
789   }
790
791   talloc_free(entry);
792   return TRP_SUCCESS;
793 }
794
795 /* select the correct route to comm/realm to be announced to peer */
796 static TRP_ROUTE *trps_select_realm_update(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer_gssname)
797 {
798   TRP_ROUTE *route;
799
800   /* Take the currently selected route unless it is through the peer we're sending the update to.
801    * I.e., enforce the split horizon rule. */
802   route=trp_rtable_get_selected_entry(trps->rtable, comm, realm);
803   if (route==NULL) {
804     /* No selected route, this should only happen if the only route has been retracted,
805      * in which case we do not want to advertise it. */
806     return NULL;
807   }
808   tr_debug("trps_select_realm_update: %s vs %s", peer_gssname->buf,
809            trp_route_get_peer(route)->buf);
810   if (0==tr_name_cmp(peer_gssname, trp_route_get_peer(route))) {
811     tr_debug("trps_select_realm_update: matched, finding alternate route");
812     /* the selected entry goes through the peer we're reporting to, choose an alternate */
813     route=trps_find_best_route(trps, comm, realm, peer_gssname);
814     if ((route==NULL) || (!trp_metric_is_finite(trp_route_get_metric(route))))
815       return NULL; /* don't advertise a nonexistent or retracted route */
816   }
817   return route;
818 }
819
820 /* returns an array of pointers to updates (*not* an array of updates). Returns number of entries
821  * via n_update parameter. (The allocated space will generally be larger than required, see note in
822  * the code.) If triggered is set, sends only triggered updates. */
823 static TRP_ROUTE **trps_select_updates_for_peer(TALLOC_CTX *memctx,
824                                                  TRPS_INSTANCE *trps,
825                                                  TR_NAME *peer_gssname,
826                                                  int triggered,
827                                                  size_t *n_update)
828 {
829   size_t n_comm=0;
830   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
831   TR_NAME **realm=NULL;
832   size_t n_realm=0;
833   size_t ii=0, jj=0;
834   TRP_ROUTE *best=NULL;
835   TRP_ROUTE **result=NULL;
836   size_t n_used=0;
837
838   /* Need to allocate space for the results. For simplicity, we just allocate a block
839    * with space for every route table entry to be returned. This is guaranteed to be large
840    * enough. If the routing table gets very large, this may be wasteful, but that seems
841    * unlikely to be significant in the near future. */
842   result=talloc_array(memctx, TRP_ROUTE *, trp_rtable_size(trps->rtable));
843   if (result==NULL) {
844     talloc_free(comm);
845     *n_update=0;
846     return NULL;
847   }
848   
849   for (ii=0; ii<n_comm; ii++) {
850     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
851     for (jj=0; jj<n_realm; jj++) {
852       best=trps_select_realm_update(trps, comm[ii], realm[jj], peer_gssname);
853       /* If we found a route, add it to the list. If triggered!=0, then only
854        * add triggered routes. */
855       if ((best!=NULL) && ((!triggered) || trp_route_is_triggered(best)))
856         result[n_used++]=best;
857     }
858     if (realm!=NULL)
859       talloc_free(realm);
860     realm=NULL;
861     n_realm=0;
862   }
863   if (comm!=NULL)
864     talloc_free(comm);
865
866   *n_update=n_used;
867   return result;
868 }
869
870 /* add metrics */
871 static unsigned int trps_metric_add(unsigned int m1, unsigned int m2)
872 {
873   if (trp_metric_is_invalid(m1) || trp_metric_is_invalid(m2))
874     return TRP_METRIC_INVALID;
875
876   if (trp_metric_is_infinite(m1) || trp_metric_is_infinite(m2))
877     return TRP_METRIC_INFINITY;
878
879   if (trp_metric_is_finite(m1+m2))
880     return m1+m2;
881   else
882     return TRP_METRIC_INFINITY;
883 }
884
885 /* convert an rentry into a new trp update info record */
886 static TRP_INFOREC *trps_route_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
887 {
888   TRP_INFOREC *rec=trp_inforec_new(mem_ctx, TRP_INFOREC_TYPE_ROUTE);
889   unsigned int linkcost=0;
890
891   if (rec!=NULL) {
892     if (trp_route_is_local(route))
893       linkcost=0;
894     else {
895       linkcost=trp_peer_get_linkcost(trps_get_peer_by_gssname(trps,
896                                                               trp_route_get_peer(route)));
897     }
898
899     /* Note that we leave the next hop empty since the recipient fills that in.
900      * This is where we add the link cost (currently always 1) to the next peer. */
901     if ((trp_inforec_set_comm(rec, trp_route_dup_comm(route)) != TRP_SUCCESS)
902        ||(trp_inforec_set_realm(rec, trp_route_dup_realm(route)) != TRP_SUCCESS)
903        ||(trp_inforec_set_trust_router(rec, trp_route_dup_trust_router(route)) != TRP_SUCCESS)
904        ||(trp_inforec_set_metric(rec,
905                                  trps_metric_add(trp_route_get_metric(route),
906                                                  linkcost)) != TRP_SUCCESS)
907        ||(trp_inforec_set_interval(rec, trps_get_update_interval(trps)) != TRP_SUCCESS)) {
908       tr_err("trps_route_to_inforec: error creating route update.");
909       talloc_free(rec);
910       rec=NULL;
911     }
912   }
913   return rec;
914 }
915
916 /* all routes to a single peer, unless comm/realm are specified (both or neither must be NULL) */
917 static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
918                                    TRP_PEER *peer,
919                                    TRP_UPDATE_TYPE update_type,
920                                    TR_NAME *comm,
921                                    TR_NAME *realm)
922 {
923   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
924   TR_MSG msg; /* not a pointer! */
925   TRP_UPD *upd=NULL;
926   TRP_ROUTE **update_list=NULL;
927   TRP_INFOREC *rec=NULL;
928   size_t n_updates=0, ii=0;
929   char *encoded=NULL;
930   TRP_RC rc=TRP_ERROR;
931   TR_NAME *peer_label=trp_peer_get_label(peer);
932
933   switch (update_type) {
934   case TRP_UPDATE_TRIGGERED:
935     tr_debug("trps_update_one_peer: preparing triggered route update for %.*s",
936              peer_label->len, peer_label->buf);
937     break;
938   case TRP_UPDATE_SCHEDULED:
939     tr_debug("trps_update_one_peer: preparing scheduled route update for %.*s",
940              peer_label->len, peer_label->buf);
941     break;
942   case TRP_UPDATE_REQUESTED:
943     tr_debug("trps_update_one_peer: preparing requested route update for %.*s",
944              peer_label->len, peer_label->buf);
945   }
946
947   /* do not fill in peer, recipient does that */
948   if ((comm==NULL) && (realm==NULL)) {
949     /* do all realms */
950     update_list=trps_select_updates_for_peer(tmp_ctx,
951                                              trps,
952                                              peer_label,
953                                              update_type==TRP_UPDATE_TRIGGERED,
954                                             &n_updates);
955   } else if ((comm!=NULL) && (realm!=NULL)) {
956     /* a single community/realm was requested */
957     update_list=talloc(tmp_ctx, TRP_ROUTE *);
958     if (update_list==NULL) {
959       tr_err("trps_update_one_peer: could not allocate update_list.");
960       rc=TRP_NOMEM;
961       goto cleanup;
962     }
963     *update_list=trps_select_realm_update(trps, comm, realm, peer_label);
964     if (*update_list==NULL) {
965       /* we have no actual update to send back, MUST send a retraction */
966       tr_debug("trps_update_one_peer: community/realm without route requested, sending mandatory retraction.");
967       *update_list=trp_route_new(update_list);
968       trp_route_set_comm(*update_list, tr_dup_name(comm));
969       trp_route_set_realm(*update_list, tr_dup_name(realm));
970       trp_route_set_peer(*update_list, tr_new_name(""));
971       trp_route_set_metric(*update_list, TRP_METRIC_INFINITY);
972       trp_route_set_trust_router(*update_list, tr_new_name(""));
973       trp_route_set_next_hop(*update_list, tr_new_name(""));
974     }
975     n_updates=1;
976   } else {
977     tr_err("trps_update_one_peer: error: only comm or realm was specified.");
978     rc=TRP_ERROR;
979     goto cleanup;
980   }
981   if ((n_updates>0) && (update_list!=NULL)) {
982     tr_debug("trps_update_one_peer: sending %u update records.", (unsigned int)n_updates);
983     upd=trp_upd_new(tmp_ctx);
984
985     for (ii=0; ii<n_updates; ii++) {
986       rec=trps_route_to_inforec(tmp_ctx, trps, update_list[ii]);
987       if (rec==NULL) {
988         tr_err("trps_update_one_peer: could not create all update records.");
989         rc=TRP_ERROR;
990         goto cleanup;
991       }
992       trp_upd_add_inforec(upd, rec);
993     }
994     talloc_free(update_list);
995     update_list=NULL;
996
997     /* now encode the update message */
998     tr_msg_set_trp_upd(&msg, upd);
999     encoded=tr_msg_encode(&msg);
1000     if (encoded==NULL) {
1001       tr_err("trps_update_one_peer: error encoding update.");
1002       rc=TRP_ERROR;
1003       goto cleanup;
1004     }
1005
1006     tr_debug("trps_update_one_peer: adding message to queue.");
1007     if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
1008       tr_err("trps_update_one_peer: error queueing update.");
1009     else
1010       tr_debug("trps_update_one_peer: update queued successfully.");
1011
1012     tr_msg_free_encoded(encoded);
1013     encoded=NULL;
1014     trp_upd_free(upd);
1015     upd=NULL;
1016   }
1017
1018 cleanup:
1019   talloc_free(tmp_ctx);
1020   return rc;
1021 }
1022
1023 /* all routes to all peers */
1024 TRP_RC trps_update(TRPS_INSTANCE *trps, TRP_UPDATE_TYPE update_type)
1025 {
1026   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1027   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
1028   TRP_PEER *peer=NULL;
1029   TRP_RC rc=TRP_SUCCESS;
1030
1031   if (trps->ptable==NULL)
1032     return TRP_SUCCESS; /* no peers, nothing to do */
1033
1034   if (iter==NULL) {
1035     tr_err("trps_update: failed to allocate peer table iterator.");
1036     talloc_free(tmp_ctx);
1037     return TRP_NOMEM;
1038   }
1039
1040   for (peer=trp_ptable_iter_first(iter, trps->ptable);
1041        peer!=NULL && rc==TRP_SUCCESS;
1042        peer=trp_ptable_iter_next(iter))
1043   {
1044     if (!trps_peer_connected(trps, peer)) {
1045       TR_NAME *peer_label=trp_peer_get_label(peer);
1046       tr_debug("trps_update: no TRP connection to %.*s, skipping.",
1047                peer_label->len, peer_label->buf);
1048       continue;
1049     }
1050     rc=trps_update_one_peer(trps, peer, update_type, NULL, NULL);
1051   }
1052   
1053   trp_ptable_iter_free(iter);
1054   trp_rtable_clear_triggered(trps->rtable); /* don't re-send triggered updates */
1055   talloc_free(tmp_ctx);
1056   return rc;
1057 }        
1058
1059 TRP_RC trps_add_route(TRPS_INSTANCE *trps, TRP_ROUTE *route)
1060 {
1061   trp_rtable_add(trps->rtable, route); /* should return status */
1062   return TRP_SUCCESS; 
1063 }
1064
1065 /* steals the peer object */
1066 TRP_RC trps_add_peer(TRPS_INSTANCE *trps, TRP_PEER *peer)
1067 {
1068   if (trps->ptable==NULL) {
1069     trps->ptable=trp_ptable_new(trps);
1070     if (trps->ptable==NULL)
1071       return TRP_NOMEM;
1072   }
1073   return trp_ptable_add(trps->ptable, peer);
1074 }
1075
1076 TRP_PEER *trps_get_peer_by_gssname(TRPS_INSTANCE *trps, TR_NAME *gssname)
1077 {
1078   if (trps->ptable==NULL)
1079     return NULL;
1080
1081   return trp_ptable_find_gss_name(trps->ptable, gssname);
1082 }
1083
1084 TRP_PEER *trps_get_peer_by_servicename(TRPS_INSTANCE *trps, TR_NAME *servicename)
1085 {
1086   if (trps->ptable==NULL)
1087     return NULL;
1088
1089   return trp_ptable_find_servicename(trps->ptable, servicename);
1090 }
1091
1092 int trps_peer_connected(TRPS_INSTANCE *trps, TRP_PEER *peer)
1093 {
1094   TRPC_INSTANCE *trpc=trps_find_trpc(trps, peer);
1095   if (trpc==NULL)
1096     return 0;
1097
1098   if (trpc_get_status(trpc)==TRP_CONNECTION_UP)
1099     return 1;
1100   else
1101     return 0;
1102 }
1103
1104
1105 static TRP_RC trps_handle_request(TRPS_INSTANCE *trps, TRP_REQ *req)
1106 {
1107   TR_NAME *comm=NULL;
1108   TR_NAME *realm=NULL;
1109
1110   tr_debug("trps_handle_request: handling TRP request.");
1111
1112   if (trps_validate_request(trps, req) != TRP_SUCCESS) {
1113     tr_notice("trps_handle_request: received invalid TRP request.");
1114     return TRP_ERROR;
1115   }
1116
1117   if (!trp_req_is_wildcard(req)) {
1118     comm=trp_req_get_comm(req);
1119     realm=trp_req_get_realm(req);
1120     tr_debug("trps_handle_request: route for %.*s/%.*s requested.",
1121              comm->len, comm->buf, realm->len, realm->buf);
1122   } else {
1123     tr_debug("trps_handle_request: all routes requested.");
1124     /* leave comm/realm NULL */
1125   }
1126   return trps_update_one_peer(trps,
1127                               trps_get_peer_by_gssname(trps, trp_req_get_peer(req)),
1128                               TRP_UPDATE_REQUESTED,
1129                               comm,
1130                               realm);
1131 }
1132
1133
1134 TRP_RC trps_handle_tr_msg(TRPS_INSTANCE *trps, TR_MSG *tr_msg)
1135 {
1136   TRP_RC rc=TRP_ERROR;
1137
1138   switch (tr_msg_get_msg_type(tr_msg)) {
1139   case TRP_UPDATE:
1140     rc=trps_handle_update(trps, tr_msg_get_trp_upd(tr_msg));
1141     if (rc==TRP_SUCCESS) {
1142       rc=trps_update_active_routes(trps);
1143       trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
1144     }
1145     return rc;
1146
1147   case TRP_REQUEST:
1148     rc=trps_handle_request(trps, tr_msg_get_trp_req(tr_msg));
1149     return rc;
1150
1151   default:
1152     /* unknown error or one we don't care about (e.g., TID messages) */
1153     return TRP_ERROR;
1154   }
1155 }
1156
1157 /* send wildcard route request to a peer */
1158 TRP_RC trps_wildcard_route_req(TRPS_INSTANCE *trps, TR_NAME *peer_servicename)
1159 {
1160   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1161   TRP_PEER *peer=trps_get_peer_by_servicename(trps, peer_servicename);
1162   TR_MSG msg; /* not a pointer */
1163   TRP_REQ *req=trp_req_new(tmp_ctx);
1164   char *encoded=NULL;
1165   TRP_RC rc=TRP_ERROR;
1166
1167   if (peer==NULL) {
1168     tr_err("trps_wildcard_route_req: unknown peer (%.*s).", peer_servicename->len, peer_servicename->buf);
1169     rc=TRP_BADARG;
1170     goto cleanup;
1171   }
1172   if ((req==NULL) || (trp_req_make_wildcard(req)!=TRP_SUCCESS)) {
1173     tr_err("trps_wildcard_route_req: unable to create wildcard TRP request.");
1174     rc=TRP_NOMEM;
1175     goto cleanup;
1176   }
1177
1178   tr_msg_set_trp_req(&msg, req);
1179   encoded=tr_msg_encode(&msg);
1180   if (encoded==NULL) {
1181     tr_err("trps_wildcard_route_req: error encoding wildcard TRP request.");
1182     rc=TRP_ERROR;
1183     goto cleanup;
1184   }
1185
1186   tr_debug("trps_wildcard_route_req: adding message to queue.");
1187   if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS) {
1188     tr_err("trps_wildcard_route_req: error queueing request.");
1189     rc=TRP_ERROR;
1190   } else {
1191     tr_debug("trps_wildcard_route_req: request queued successfully.");
1192     rc=TRP_SUCCESS;
1193   }
1194
1195 cleanup:
1196   if (encoded!=NULL)
1197     tr_msg_free_encoded(encoded);
1198   if (req!=NULL)
1199     trp_req_free(req);
1200
1201   talloc_free(tmp_ctx);
1202   return rc;
1203 }