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