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