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