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