Don't send communities in triggered updates. Comms now flood!
[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 /* Get the label peers will know us by - needs to match trp_peer_get_label() output.
190  * There is no get, only dup, because we don't store the label except when requested. */
191 TR_NAME *trps_dup_label(TRPS_INSTANCE *trps)
192 {
193   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
194   TR_NAME *label=NULL;
195   char *s=talloc_asprintf(tmp_ctx, "%s:%u", trps->hostname, trps->port);
196   if (s==NULL)
197     goto cleanup;
198   label=tr_new_name(s);
199
200 cleanup:
201   talloc_free(tmp_ctx);
202   return label;
203 }
204
205 TRPC_INSTANCE *trps_find_trpc(TRPS_INSTANCE *trps, TRP_PEER *peer)
206 {
207   TRPC_INSTANCE *cur=NULL;
208   TR_NAME *name=NULL;
209   TR_NAME *peer_servicename=trp_peer_get_servicename(peer);
210
211   for (cur=trps->trpc; cur!=NULL; cur=trpc_get_next(cur)) {
212     name=trpc_get_gssname(cur);
213     if ((name!=NULL) && (0==tr_name_cmp(peer_servicename, name))) {
214       break;
215     }
216   }
217   return cur;
218 }
219
220 void trps_add_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *new)
221 {
222   if (trps->conn==NULL)
223     trps->conn=new;
224   else
225     trp_connection_append(trps->conn, new);
226
227   talloc_steal(trps, new);
228 }
229
230 /* ok to call more than once; guarantees connection no longer in the list.
231  * Caller is responsible for freeing the removed element afterwards.  */
232 void trps_remove_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *remove)
233 {
234   trps->conn=trp_connection_remove(trps->conn, remove);
235 }
236
237 void trps_add_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *trpc)
238 {
239   if (trps->trpc==NULL)
240     trps->trpc=trpc;
241   else
242     trpc_append(trps->trpc, trpc);
243
244   talloc_steal(trps, trpc);
245 }
246
247 /* ok to call more than once; guarantees trpc no longer in the list.
248  * Caller is responsible for freeing the removed element afterwards.  */
249 void trps_remove_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *remove)
250 {
251   trps->trpc=trpc_remove(trps->trpc, remove);
252 }
253
254 TRP_RC trps_send_msg(TRPS_INSTANCE *trps, TRP_PEER *peer, const char *msg)
255 {
256   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
257   TR_MQ_MSG *mq_msg=NULL;
258   char *msg_dup=NULL;
259   TRP_RC rc=TRP_ERROR;
260   TRPC_INSTANCE *trpc=NULL;
261
262   /* get the connection for this peer */
263   trpc=trps_find_trpc(trps, peer);
264   /* instead, let's let that happen and then clear the queue when an attempt to
265    * connect fails */
266   if (trpc==NULL) {
267     tr_warning("trps_send_msg: skipping message queued for missing TRP client entry.");
268   } else {
269     mq_msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_SEND, TR_MQ_PRIO_NORMAL);
270     msg_dup=talloc_strdup(mq_msg, msg); /* get local copy in mq_msg context */
271     tr_mq_msg_set_payload(mq_msg, msg_dup, NULL); /* no need for a free() func */
272     trpc_mq_add(trpc, mq_msg);
273     rc=TRP_SUCCESS;
274   }
275   talloc_free(tmp_ctx);
276   return rc;
277 }
278
279 static int trps_listen (TRPS_INSTANCE *trps, int port) 
280 {
281   int rc = 0;
282   int conn = -1;
283   int optval = 1;
284
285   union {
286     struct sockaddr_storage storage;
287     struct sockaddr_in in4;
288   } addr;
289
290   struct sockaddr_in *saddr = (struct sockaddr_in *) &addr.in4;
291
292   saddr->sin_port = htons (port);
293   saddr->sin_family = AF_INET;
294   saddr->sin_addr.s_addr = INADDR_ANY;
295
296   if (0 > (conn = socket (AF_INET, SOCK_STREAM, 0)))
297     return conn;
298
299   setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
300
301   if (0 > (rc = bind (conn, (struct sockaddr *) saddr, sizeof(struct sockaddr_in))))
302     return rc;
303
304   if (0 > (rc = listen(conn, 512)))
305     return rc;
306
307   tr_debug("trps_listen: TRP Server listening on port %d", port);
308   return conn;
309 }
310
311 /* get the currently selected route if available */
312 TRP_ROUTE *trps_get_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
313 {
314   return trp_rtable_get_entry(trps->rtable, comm, realm, peer);
315 }
316
317 TRP_ROUTE *trps_get_selected_route(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
318 {
319   tr_debug("trps_get_selected_route: entered. trps=%p, comm=%p, realm=%p", trps, comm, realm);
320   return trp_rtable_get_selected_entry(trps->rtable, comm, realm);
321 }
322
323 /* copy the result if you want to keep it */
324 TR_NAME *trps_get_next_hop(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm)
325 {
326   TRP_ROUTE *route=trps_get_selected_route(trps, comm, realm);
327   if (route==NULL)
328     return NULL;
329
330   return trp_route_get_next_hop(route);
331 }
332
333
334 /* mark a route as retracted */
335 static void trps_retract_route(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
336 {
337   trp_route_set_metric(entry, TRP_METRIC_INFINITY);
338   trp_route_set_triggered(entry, 1);
339 }
340
341 /* is this route retracted? */
342 static int trps_route_retracted(TRPS_INSTANCE *trps, TRP_ROUTE *entry)
343 {
344   return (trp_metric_is_infinite(trp_route_get_metric(entry)));
345 }
346
347 static TRP_RC trps_read_message(TRPS_INSTANCE *trps, TRP_CONNECTION *conn, TR_MSG **msg)
348 {
349   int err=0;
350   char *buf=NULL;
351   size_t buflen = 0;
352   TRP_PEER *peer=NULL; /* entry in the peer table */
353   TR_NAME *conn_peer=NULL; /* name from the TRP_CONN, which comes from the gss context */
354
355   tr_debug("trps_read_message: started");
356   if (err = gsscon_read_encrypted_token(trp_connection_get_fd(conn),
357                                        *(trp_connection_get_gssctx(conn)), 
358                                        &buf,
359                                        &buflen)) {
360     tr_debug("trps_read_message: error");
361     if (buf)
362       free(buf);
363     return TRP_ERROR;
364   }
365
366   tr_debug("trps_read_message: message received, %u bytes.", (unsigned) buflen);
367   tr_debug("trps_read_message: %.*s", buflen, buf);
368
369   *msg=tr_msg_decode(buf, buflen);
370   free(buf);
371   if (*msg==NULL)
372     return TRP_NOPARSE;
373
374   conn_peer=trp_connection_get_peer(conn);
375   if (conn_peer==NULL) {
376     tr_err("trps_read_message: connection has no peer name");
377     return TRP_ERROR;
378   }
379
380   peer=trps_get_peer_by_gssname(trps, conn_peer);
381   if (peer==NULL) {
382     tr_err("trps_read_message: could not find peer with gssname=%s", trp_connection_get_gssname(conn));
383     return TRP_ERROR;
384   }
385
386   /* verify we received a message we support, otherwise drop it now */
387   switch (tr_msg_get_msg_type(*msg)) {
388   case TRP_UPDATE:
389     trp_upd_set_peer(tr_msg_get_trp_upd(*msg), tr_dup_name(conn_peer));
390     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 */
391     break;
392
393   case TRP_REQUEST:
394     trp_req_set_peer(tr_msg_get_trp_req(*msg), tr_dup_name(conn_peer));
395     break;
396
397   default:
398     tr_debug("trps_read_message: received unsupported message from %.*s", conn_peer->len, conn_peer->buf);
399     tr_msg_free_decoded(*msg);
400     *msg=NULL;
401     return TRP_UNSUPPORTED;
402   }
403   
404   return TRP_SUCCESS;
405 }
406
407 int trps_get_listener(TRPS_INSTANCE *trps,
408                       TRPS_MSG_FUNC msg_handler,
409                       TRP_AUTH_FUNC auth_handler,
410                       const char *hostname,
411                       unsigned int port,
412                       void *cookie)
413 {
414   int listen = -1;
415
416   if (0 > (listen = trps_listen(trps, port))) {
417     char errbuf[256];
418     if (0 == strerror_r(errno, errbuf, 256)) {
419       tr_debug("trps_get_listener: Error opening port %d: %s.", port, errbuf);
420     } else {
421       tr_debug("trps_get_listener: Unknown error openining port %d.", port);
422     }
423   } 
424
425   if (listen > 0) {
426     /* opening port succeeded */
427     tr_debug("trps_get_listener: Opened port %d.", port);
428     
429     /* make this socket non-blocking */
430     if (0 != fcntl(listen, F_SETFL, O_NONBLOCK)) {
431       tr_debug("trps_get_listener: Error setting O_NONBLOCK.");
432       close(listen);
433       listen=-1;
434     }
435   }
436
437   if (listen > 0) {
438     /* store the caller's request handler & cookie */
439     trps->msg_handler = msg_handler;
440     trps->auth_handler = auth_handler;
441     trps->hostname = talloc_strdup(trps, hostname);
442     trps->port = port;
443     trps->cookie = cookie;
444   }
445
446   return listen;
447 }
448
449 TRP_RC trps_authorize_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
450 {
451   /* try to establish a GSS context */
452   if (0!=trp_connection_auth(conn, trps->auth_handler, trps->cookie)) {
453     tr_notice("trps_authorize_connection: failed to authorize connection");
454     trp_connection_close(conn);
455     return TRP_ERROR;
456   }
457   tr_notice("trps_authorize_connection: authorized connection");
458   return TRP_SUCCESS;
459 }
460
461 void trps_handle_connection(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
462 {
463   TR_MSG *msg=NULL;
464   TRP_RC rc=TRP_ERROR;
465
466   /* loop as long as the connection exists */
467   while (trp_connection_get_status(conn)==TRP_CONNECTION_UP) {
468     rc=trps_read_message(trps, conn, &msg);
469     switch(rc) {
470     case TRP_SUCCESS:
471       trps->msg_handler(trps, conn, msg); /* send the TR_MSG off to the callback */
472       break;
473
474     case TRP_ERROR:
475       trp_connection_close(conn);
476       break;
477
478     default:
479       tr_debug("trps_handle_connection: trps_read_message failed (%d)", rc);
480     }
481   }
482
483   tr_debug("trps_handle_connection: connection closed.");
484 }
485
486 /* TODO: check realm/comm, now part of the update instead of inforec */
487 static TRP_RC trps_validate_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
488 {
489   if (upd==NULL) {
490     tr_notice("trps_validate_update: null TRP update.");
491     return TRP_BADARG;
492   }
493
494   if (trp_upd_get_realm(upd)==NULL) {
495     tr_notice("trps_validate_update: received TRP update without realm.");
496     return TRP_ERROR;
497   }
498
499   if (trp_upd_get_comm(upd)==NULL) {
500     tr_notice("trps_validate_update: received TRP update without community.");
501     return TRP_ERROR;
502   }
503
504   if (trp_upd_get_inforec(upd)==NULL) {
505     tr_notice("trps_validate_update: received TRP update with no info records.");
506     return TRP_ERROR;
507   }
508
509   if (trp_upd_get_peer(upd)==NULL) {
510     tr_notice("trps_validate_update: received TRP update without origin peer information.");
511     return TRP_ERROR;
512   }
513
514   
515   return TRP_SUCCESS;
516 }
517
518 /* ensure that the update could be accepted if feasible */
519 static TRP_RC trps_validate_inforec(TRPS_INSTANCE *trps, TRP_INFOREC *rec)
520 {
521   switch(trp_inforec_get_type(rec)) {
522   case TRP_INFOREC_TYPE_ROUTE:
523     if ((trp_inforec_get_trust_router(rec)==NULL)
524        || (trp_inforec_get_next_hop(rec)==NULL)) {
525       tr_debug("trps_validate_inforec: missing record info.");
526       return TRP_ERROR;
527     }
528
529     /* check for valid metric */
530     if (trp_metric_is_invalid(trp_inforec_get_metric(rec))) {
531       tr_debug("trps_validate_inforec: invalid metric (%u).", trp_inforec_get_metric(rec));
532       return TRP_ERROR;
533     }
534
535     /* check for valid interval */
536     if (trp_inforec_get_interval(rec)==TRP_INTERVAL_INVALID) {
537       tr_debug("trps_validate_inforec: invalid interval.");
538       return TRP_ERROR;
539     }
540     break;
541
542   case TRP_INFOREC_TYPE_COMMUNITY:
543     /* TODO: validate community updates */
544     break;
545     
546   default:
547     tr_notice("trps_validate_inforec: unsupported record type.");
548     return TRP_UNSUPPORTED;
549   }
550
551   return TRP_SUCCESS;
552 }
553
554 /* link cost to a peer */
555 static unsigned int trps_cost(TRPS_INSTANCE *trps, TR_NAME *peer)
556 {
557   return 1;
558 }
559
560 static unsigned int trps_advertised_metric(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer)
561 {
562   TRP_ROUTE *entry=trp_rtable_get_entry(trps->rtable, comm, realm, peer);
563   if (entry==NULL)
564     return TRP_METRIC_INFINITY;
565   return trp_route_get_metric(entry) + trps_cost(trps, peer);
566 }
567
568 static int trps_check_feasibility(TRPS_INSTANCE *trps, TR_NAME *realm, TR_NAME *comm, TRP_INFOREC *rec)
569 {
570   unsigned int rec_metric=trp_inforec_get_metric(rec);
571   unsigned int new_metric=0;
572   unsigned int current_metric=0;
573   TR_NAME *next_hop=NULL;
574
575   /* we check these in the validation stage, but just in case... */
576   if (trp_metric_is_invalid(rec_metric))
577     return 0;
578
579   /* retractions (aka infinite metrics) are always feasible */
580   if (trp_metric_is_infinite(rec_metric))
581     return 1;
582
583   /* updates from our current next hop are always feasible*/
584   next_hop=trps_get_next_hop(trps, comm, realm);
585   if ((next_hop!=NULL)
586      && (0==tr_name_cmp(next_hop,trp_inforec_get_next_hop(rec)))) {
587     return 1;
588   }
589     
590
591   /* compare the existing metric we advertise to what we would advertise
592    * if we accept this update */
593   current_metric=trps_advertised_metric(trps, comm, realm, trp_inforec_get_next_hop(rec));
594   new_metric=rec_metric + trps_cost(trps, trp_inforec_get_next_hop(rec));
595   if (new_metric <= current_metric)
596     return 1;
597   else
598     return 0;
599 }
600
601 /* uses memory pointed to by *ts, also returns that value. On error, its contents are {0,0} */
602 static struct timespec *trps_compute_expiry(TRPS_INSTANCE *trps, unsigned int interval, struct timespec *ts)
603 {
604   const unsigned int small_factor=3; /* how many intervals we wait before expiring */
605   if (0!=clock_gettime(CLOCK_REALTIME, ts)) {
606     tr_err("trps_compute_expiry: could not read realtime clock.");
607     ts->tv_sec=0;
608     ts->tv_nsec=0;
609   }
610   ts->tv_sec += small_factor*interval;
611   return ts;
612 }
613
614 static TRP_RC trps_accept_update(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
615 {
616   TRP_ROUTE *entry=NULL;
617
618   entry=trp_rtable_get_entry(trps->rtable,
619                              trp_upd_get_comm(upd),
620                              trp_upd_get_realm(upd),
621                              trp_inforec_get_next_hop(rec));
622   if (entry==NULL) {
623     entry=trp_route_new(NULL);
624     if (entry==NULL) {
625       tr_err("trps_accept_update: unable to allocate new entry.");
626       return TRP_NOMEM;
627     }
628
629     trp_route_set_comm(entry, trp_upd_dup_comm(upd));
630     trp_route_set_realm(entry, trp_upd_dup_realm(upd));
631     trp_route_set_peer(entry, trp_upd_dup_peer(upd));
632     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec));
633     trp_route_set_next_hop(entry, trp_inforec_dup_next_hop(rec));
634     /* TODO: pass next hop port (now defaults to TID_PORT) --jlr */
635     if ((trp_route_get_comm(entry)==NULL)
636        ||(trp_route_get_realm(entry)==NULL)
637        ||(trp_route_get_peer(entry)==NULL)
638        ||(trp_route_get_trust_router(entry)==NULL)
639        ||(trp_route_get_next_hop(entry)==NULL)) {
640       /* at least one field could not be allocated */
641       tr_err("trps_accept_update: unable to allocate all fields for entry.");
642       trp_route_free(entry);
643       return TRP_NOMEM;
644     }
645     trp_rtable_add(trps->rtable, entry);
646   }
647
648   /* We now have an entry in the table, whether it's new or not. Update metric and expiry, unless
649    * the metric is infinity. An infinite metric can only occur here if we just retracted an existing
650    * route (we never accept retractions as new routes), so there is no risk of leaving the expiry
651    * time unset on a new route entry. */
652   tr_debug("trps_accept_update: accepting route update.");
653   trp_route_set_metric(entry, trp_inforec_get_metric(rec));
654   trp_route_set_interval(entry, trp_inforec_get_interval(rec));
655
656   /* check whether the trust router has changed */
657   if (0!=tr_name_cmp(trp_route_get_trust_router(entry),
658                      trp_inforec_get_trust_router(rec))) {
659     /* The name changed. Set this route as triggered. */
660     tr_debug("trps_accept_update: trust router for route changed.");
661     trp_route_set_triggered(entry, 1);
662     trp_route_set_trust_router(entry, trp_inforec_dup_trust_router(rec)); /* frees old name */
663   }
664   if (!trps_route_retracted(trps, entry)) {
665     tr_debug("trps_accept_update: route not retracted, setting expiry timer.");
666     trp_route_set_expiry(entry, trps_compute_expiry(trps,
667                                                      trp_route_get_interval(entry),
668                                                      trp_route_get_expiry(entry)));
669   }
670   return TRP_SUCCESS;
671 }
672
673
674 static TRP_RC trps_handle_inforec_route(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
675 {
676   TRP_ROUTE *route=NULL;
677   unsigned int feas=0;
678
679   /* determine feasibility */
680   feas=trps_check_feasibility(trps, trp_upd_get_realm(upd), trp_upd_get_comm(upd), rec);
681   tr_debug("trps_handle_update: record feasibility=%d", feas);
682
683   /* do we have an existing route? */
684   route=trps_get_route(trps,
685                        trp_upd_get_comm(upd),
686                        trp_upd_get_realm(upd),
687                        trp_upd_get_peer(upd));
688   if (route!=NULL) {
689     /* there was a route table entry already */
690     tr_debug("trps_handle_updates: route entry already exists.");
691     if (feas) {
692       /* Update is feasible. Accept it. */
693       trps_accept_update(trps, upd, rec);
694     } else {
695       /* Update is infeasible. Ignore it unless the trust router has changed. */
696       if (0!=tr_name_cmp(trp_route_get_trust_router(route),
697                          trp_inforec_get_trust_router(rec))) {
698         /* the trust router associated with the route has changed, treat update as a retraction */
699         trps_retract_route(trps, route);
700       }
701     }
702   } else {
703     /* No existing route table entry. Ignore it unless it is feasible and not a retraction. */
704     tr_debug("trps_handle_update: no route entry exists yet.");
705     if (feas && trp_metric_is_finite(trp_inforec_get_metric(rec)))
706       trps_accept_update(trps, upd, rec);
707   }
708
709   return TRP_SUCCESS;
710 }
711
712 static int trps_name_in_provenance(TR_NAME *name, json_t *prov)
713 {
714   size_t ii=0;
715   TR_NAME *this_name=NULL;
716   const char *s=NULL;
717
718   if (prov==NULL)
719     return 0; /* no provenance list, so it has no names in it */
720
721   /* now check to see if name is in the provenance */
722   for (ii=0; ii<json_array_size(prov); ii++) {
723     s=json_string_value(json_array_get(prov, ii));
724     if (s==NULL) {
725       tr_debug("trps_name_in_provenance: empty entry in provenance list.");
726       continue;
727     }
728
729     this_name=tr_new_name(s);
730     if (this_name==NULL) {
731       tr_debug("trps_name_in_provenance: unable to allocate name.");
732       return -1;
733     }
734     if (0==tr_name_cmp(name, this_name)) {
735       tr_free_name(this_name);
736       return 1;
737     }
738     tr_free_name(this_name);
739   }
740   return 0;
741 }
742
743 static TR_COMM *trps_create_new_comm(TALLOC_CTX *mem_ctx, TR_NAME *comm_id, TRP_INFOREC *rec)
744 {
745   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
746   TR_COMM *comm=tr_comm_new(tmp_ctx);
747   
748   if (comm==NULL) {
749     tr_debug("trps_create_new_comm: unable to allocate new community.");
750     goto cleanup;
751   }
752   /* fill in the community with info */
753   tr_comm_set_id(comm, tr_dup_name(comm_id));
754   if (tr_comm_get_id(comm)==NULL) {
755     tr_debug("trps_create_new_comm: unable to allocate community name.");
756     comm=NULL;
757     goto cleanup;
758   }
759   tr_comm_set_type(comm, trp_inforec_get_comm_type(rec));
760   if (trp_inforec_get_apcs(rec)!=NULL) {
761     tr_comm_set_apcs(comm, tr_apc_dup(tmp_ctx, trp_inforec_get_apcs(rec)));
762     if (tr_comm_get_apcs(comm)==NULL) {
763       tr_debug("trps_create_new_comm: unable to allocate APC list.");
764       comm=NULL;
765       goto cleanup;
766     }
767   }
768   if (trp_inforec_get_owner_realm(rec)!=NULL) {
769     tr_comm_set_owner_realm(comm, tr_dup_name(trp_inforec_get_owner_realm(rec)));
770     if (tr_comm_get_owner_realm(comm)==NULL) {
771       tr_debug("trps_create_new_comm: unable to allocate owner realm name.");
772       comm=NULL;
773       goto cleanup;
774     }
775   }
776   if (trp_inforec_get_owner_contact(rec)!=NULL) {
777     tr_comm_set_owner_contact(comm, tr_dup_name(trp_inforec_get_owner_contact(rec)));
778     if (tr_comm_get_owner_contact(comm)==NULL) {
779       tr_debug("trps_create_new_comm: unable to allocate owner contact.");
780       comm=NULL;
781       goto cleanup;
782     }
783   }
784   comm->expiration_interval=trp_inforec_get_exp_interval(rec);
785   talloc_steal(mem_ctx, comm);
786   
787 cleanup:
788   talloc_free(tmp_ctx);
789   return comm;
790 }
791
792 static TR_RP_REALM *trps_create_new_rp_realm(TALLOC_CTX *mem_ctx, TR_NAME *realm_id, TRP_INFOREC *rec)
793 {
794   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
795   TR_RP_REALM *rp=tr_rp_realm_new(tmp_ctx);
796   
797   if (rp==NULL) {
798     tr_debug("trps_create_new_rp_realm: unable to allocate new realm.");
799     goto cleanup;
800   }
801   /* fill in the realm */
802   tr_rp_realm_set_id(rp, tr_dup_name(realm_id));
803   if (tr_rp_realm_get_id(rp)==NULL) {
804     tr_debug("trps_create_new_rp_realm: unable to allocate realm name.");
805     rp=NULL;
806     goto cleanup;
807   }
808   talloc_steal(mem_ctx, rp);
809   
810 cleanup:
811   talloc_free(tmp_ctx);
812   return rp;
813 }
814
815 static TR_IDP_REALM *trps_create_new_idp_realm(TALLOC_CTX *mem_ctx, TR_NAME *realm_id, TRP_INFOREC *rec)
816 {
817   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
818   TR_IDP_REALM *idp=tr_idp_realm_new(tmp_ctx);
819   
820   if (idp==NULL) {
821     tr_debug("trps_create_new_idp_realm: unable to allocate new realm.");
822     goto cleanup;
823   }
824   /* fill in the realm */
825   tr_idp_realm_set_id(idp, tr_dup_name(realm_id));
826   if (tr_idp_realm_get_id(idp)==NULL) {
827     tr_debug("trps_create_new_idp_realm: unable to allocate realm name.");
828     idp=NULL;
829     goto cleanup;
830   }
831   if (trp_inforec_get_apcs(rec)!=NULL) {
832     tr_idp_realm_set_apcs(idp, tr_apc_dup(tmp_ctx, trp_inforec_get_apcs(rec)));
833     if (tr_idp_realm_get_apcs(idp)==NULL) {
834       tr_debug("trps_create_new_idp_realm: unable to allocate APC list.");
835       idp=NULL;
836       goto cleanup;
837     }
838   }
839   idp->origin=TR_REALM_DISCOVERED;
840   
841   talloc_steal(mem_ctx, idp);
842   
843 cleanup:
844   talloc_free(tmp_ctx);
845   return idp;
846 }
847
848 static TRP_RC trps_handle_inforec_comm(TRPS_INSTANCE *trps, TRP_UPD *upd, TRP_INFOREC *rec)
849 {
850   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
851   TR_NAME *comm_id=trp_upd_get_comm(upd);
852   TR_NAME *realm_id=trp_upd_get_realm(upd);
853   TR_NAME *origin_id=NULL;
854   TR_NAME *our_peer_label=NULL;
855   TR_COMM *comm=NULL;
856   TR_RP_REALM *rp_realm=NULL;
857   TR_IDP_REALM *idp_realm=NULL;
858   struct timespec expiry={0,0};
859   TRP_RC rc=TRP_ERROR;
860
861   if ((comm_id==NULL) || (realm_id==NULL))
862     goto cleanup;
863
864   origin_id=trp_inforec_dup_origin(rec);
865   if (origin_id==NULL)
866     goto cleanup;
867     
868   /* see whether we want to add this */
869   our_peer_label=trps_dup_label(trps);
870   if (our_peer_label==NULL) {
871     tr_debug("trps_handle_inforec_comm: unable to allocate peer label.");
872     goto cleanup;
873   }
874
875   if (trps_name_in_provenance(our_peer_label, trp_inforec_get_provenance(rec)))
876     tr_debug("trps_handle_inforec_comm: rejecting community inforec to avoid loop.");
877   else {
878     /* no loop occurring, accept the update */
879     comm=tr_comm_table_find_comm(trps->ctable, comm_id);
880     if (comm==NULL) {
881       tr_debug("trps_handle_inforec_comm: unknown community %.*s in inforec, creating it.",
882                comm_id->len, comm_id->buf);
883       comm=trps_create_new_comm(tmp_ctx, comm_id, rec);
884       if (comm==NULL) {
885         tr_debug("trps_handle_inforec_comm: unable to create new community.");
886         goto cleanup;
887       }
888       tr_comm_table_add_comm(trps->ctable, comm);
889     }
890     /* TODO: see if other comm data match the new inforec and update or complain */
891
892     trps_compute_expiry(trps, trp_inforec_get_interval(rec), &expiry);
893     if ((expiry.tv_sec==0)&&(expiry.tv_nsec==0))
894       goto cleanup;
895
896     switch (trp_inforec_get_role(rec)) {
897     case TR_ROLE_RP:
898       rp_realm=tr_rp_realm_lookup(trps->ctable->rp_realms, realm_id);
899       if (rp_realm==NULL) {
900         tr_debug("trps_handle_inforec_comm: unknown RP realm %.*s in inforec, creating it.",
901                  realm_id->len, realm_id->buf);
902         rp_realm=trps_create_new_rp_realm(tmp_ctx, realm_id, rec);
903         if (rp_realm==NULL) {
904           tr_debug("trps_handle_inforec_comm: unable to create new RP realm.");
905           /* we may leave an unused community in the table, but it will only last until
906            * the next table sweep if it does not get any realms before that happens */
907           goto cleanup;
908         }
909         tr_rp_realm_add(trps->ctable->rp_realms, rp_realm);
910       }
911       /* TODO: if realm existed, see if data match the new inforec and update or complain */
912       tr_comm_add_rp_realm(trps->ctable, comm, rp_realm, trp_inforec_get_provenance(rec), &expiry);
913       tr_debug("trps_handle_inforec_comm: added RP realm %.*s to comm %.*s (origin %.*s).",
914                realm_id->len, realm_id->buf,
915                comm_id->len, comm_id->buf,
916                origin_id->len, origin_id->buf);
917       break;
918     case TR_ROLE_IDP:
919       idp_realm=tr_idp_realm_lookup(trps->ctable->idp_realms, realm_id);
920       if (idp_realm==NULL) {
921         tr_debug("trps_handle_inforec_comm: unknown IDP realm %.*s in inforec, creating it.",
922                  realm_id->len, realm_id->buf);
923         idp_realm=trps_create_new_idp_realm(tmp_ctx, realm_id, rec);
924         if (idp_realm==NULL) {
925           tr_debug("trps_handle_inforec_comm: unable to create new IDP realm.");
926           /* we may leave an unused community in the table, but it will only last until
927            * the next table sweep if it does not get any realms before that happens */
928           goto cleanup;
929         }
930         tr_idp_realm_add(trps->ctable->idp_realms, idp_realm);
931       }
932       /* TODO: if realm existed, see if data match the new inforec and update or complain */
933       tr_comm_add_idp_realm(trps->ctable, comm, idp_realm, trp_inforec_get_provenance(rec), &expiry);
934       tr_debug("trps_handle_inforec_comm: added IDP realm %.*s to comm %.*s (origin %.*s).",
935                realm_id->len, realm_id->buf,
936                comm_id->len, comm_id->buf,
937                origin_id->len, origin_id->buf);
938       break;
939     default:
940       tr_debug("trps_handle_inforec_comm: unable to add realm.");
941       goto cleanup;
942     }
943   } 
944
945   rc=TRP_SUCCESS;
946
947 cleanup:
948   if (our_peer_label!=NULL)
949     tr_free_name(our_peer_label);
950   if (origin_id!=NULL)
951     tr_free_name(origin_id);
952   talloc_free(tmp_ctx);
953   return rc;
954 }
955
956 static TRP_RC trps_handle_update(TRPS_INSTANCE *trps, TRP_UPD *upd)
957 {
958   TRP_INFOREC *rec=NULL;
959
960   if (trps_validate_update(trps, upd) != TRP_SUCCESS) {
961     tr_notice("trps_handle_update: received invalid TRP update.");
962     return TRP_ERROR;
963   }
964
965   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
966     /* validate/sanity check the record update */
967     if (trps_validate_inforec(trps, rec) != TRP_SUCCESS) {
968       tr_notice("trps_handle_update: invalid inforec in TRP update, discarding entire update.");
969       return TRP_ERROR;
970     }
971   }
972
973   for (rec=trp_upd_get_inforec(upd); rec!=NULL; rec=trp_inforec_get_next(rec)) {
974     switch (trp_inforec_get_type(rec)) {
975     case TRP_INFOREC_TYPE_ROUTE:
976       tr_debug("trps_handle_update: handling route inforec.");
977       if (TRP_SUCCESS!=trps_handle_inforec_route(trps, upd, rec))
978         tr_notice("trps_handle_update: error handling route inforec.");
979       break;
980     case TRP_INFOREC_TYPE_COMMUNITY:
981       tr_debug("trps_handle_update: handling community inforec.");
982       if (TRP_SUCCESS!=trps_handle_inforec_comm(trps, upd, rec))
983         tr_notice("trps_handle_update: error handling community inforec.");
984       break;
985     default:
986       tr_notice("trps_handle_update: unsupported inforec in TRP update.");
987       break;
988     }
989   }
990   return TRP_SUCCESS;
991 }
992
993 static TRP_RC trps_validate_request(TRPS_INSTANCE *trps, TRP_REQ *req)
994 {
995   if (req==NULL) {
996     tr_notice("trps_validate_request: null TRP request.");
997     return TRP_BADARG;
998   }
999
1000   if (trp_req_get_comm(req)==NULL) {
1001     tr_notice("trps_validate_request: received TRP request with null community.");
1002     return TRP_ERROR;
1003   }
1004   
1005   if (trp_req_get_realm(req)==NULL) {
1006     tr_notice("trps_validate_request: received TRP request with null realm.");
1007     return TRP_ERROR;
1008   }
1009   
1010   if (trp_req_get_peer(req)==NULL) {
1011     tr_notice("trps_validate_request: received TRP request without origin peer information.");
1012     return TRP_ERROR;
1013   }
1014   
1015   return TRP_SUCCESS;
1016 }
1017
1018 /* choose the best route to comm/realm, optionally excluding routes to a particular peer */
1019 static TRP_ROUTE *trps_find_best_route(TRPS_INSTANCE *trps,
1020                                         TR_NAME *comm,
1021                                         TR_NAME *realm,
1022                                         TR_NAME *exclude_peer)
1023 {
1024   TRP_ROUTE **entry=NULL;
1025   TRP_ROUTE *best=NULL;
1026   size_t n_entry=0;
1027   unsigned int kk=0;
1028   unsigned int kk_min=0;
1029   unsigned int min_metric=TRP_METRIC_INFINITY;
1030
1031   entry=trp_rtable_get_realm_entries(trps->rtable, comm, realm, &n_entry);
1032   for (kk=0; kk<n_entry; kk++) {
1033     if (trp_route_get_metric(entry[kk]) < min_metric) {
1034       if ((exclude_peer==NULL) || (0!=tr_name_cmp(trp_route_get_peer(entry[kk]),
1035                                                   exclude_peer))) {
1036         kk_min=kk;
1037         min_metric=trp_route_get_metric(entry[kk]);
1038       } 
1039     }
1040   }
1041   if (trp_metric_is_finite(min_metric))
1042     best=entry[kk_min];
1043   
1044   talloc_free(entry);
1045   return best;
1046 }
1047
1048 /* TODO: think this through more carefully. At least ought to add hysteresis
1049  * to avoid flapping between routers or routes. */
1050 TRP_RC trps_update_active_routes(TRPS_INSTANCE *trps)
1051 {
1052   size_t n_comm=0, ii=0;
1053   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
1054   size_t n_realm=0, jj=0;
1055   TR_NAME **realm=NULL;
1056   TRP_ROUTE *best_route=NULL, *cur_route=NULL;
1057   unsigned int best_metric=0, cur_metric=0;
1058
1059   for (ii=0; ii<n_comm; ii++) {
1060     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
1061     for (jj=0; jj<n_realm; jj++) {
1062       best_route=trps_find_best_route(trps, comm[ii], realm[jj], NULL);
1063       if (best_route==NULL)
1064         best_metric=TRP_METRIC_INFINITY;
1065       else
1066         best_metric=trp_route_get_metric(best_route);
1067
1068       cur_route=trps_get_selected_route(trps, comm[ii], realm[jj]);
1069       if (cur_route!=NULL) {
1070         cur_metric=trp_route_get_metric(cur_route);
1071         if ((best_metric < cur_metric) && (trp_metric_is_finite(best_metric))) {
1072           /* The new route has a lower metric than the previous, and is finite. Accept. */
1073           trp_route_set_selected(cur_route, 0);
1074           trp_route_set_selected(best_route, 1);
1075         } else if (!trp_metric_is_finite(cur_metric)) /* rejects infinite or invalid metrics */
1076           trp_route_set_selected(cur_route, 0);
1077       } else if (trp_metric_is_finite(best_metric)) {
1078         trp_route_set_selected(best_route, 1);
1079       }
1080     }
1081     if (realm!=NULL)
1082       talloc_free(realm);
1083     realm=NULL; n_realm=0;
1084   }
1085   if (comm!=NULL)
1086     talloc_free(comm);
1087   comm=NULL; n_comm=0;
1088
1089   return TRP_SUCCESS;
1090 }
1091
1092 /* true if curtime >= expiry */
1093 static int trps_expired(struct timespec *expiry, struct timespec *curtime)
1094 {
1095   return ((curtime->tv_sec > expiry->tv_sec)
1096          || ((curtime->tv_sec == expiry->tv_sec)
1097             &&(curtime->tv_nsec >= expiry->tv_nsec)));
1098 }
1099
1100 /* Sweep for expired routes. For each expired route, if its metric is infinite, the route is flushed.
1101  * If its metric is finite, the metric is set to infinite and the route's expiration time is updated. */
1102 TRP_RC trps_sweep_routes(TRPS_INSTANCE *trps)
1103 {
1104   struct timespec sweep_time={0,0};
1105   TRP_ROUTE **entry=NULL;
1106   size_t n_entry=0;
1107   size_t ii=0;
1108
1109   /* use a single time for the entire sweep */
1110   if (0!=clock_gettime(CLOCK_REALTIME, &sweep_time)) {
1111     tr_err("trps_sweep_routes: could not read realtime clock.");
1112     sweep_time.tv_sec=0;
1113     sweep_time.tv_nsec=0;
1114     return TRP_ERROR;
1115   }
1116
1117   entry=trp_rtable_get_entries(trps->rtable, &n_entry); /* must talloc_free *entry */
1118
1119   /* loop over the entries */
1120   for (ii=0; ii<n_entry; ii++) {
1121     if (!trp_route_is_local(entry[ii]) && trps_expired(trp_route_get_expiry(entry[ii]), &sweep_time)) {
1122       tr_debug("trps_sweep_routes: route expired.");
1123       if (!trp_metric_is_finite(trp_route_get_metric(entry[ii]))) {
1124         /* flush route */
1125         tr_debug("trps_sweep_routes: metric was infinity, flushing route.");
1126         trp_rtable_remove(trps->rtable, entry[ii]); /* entry[ii] is no longer valid */
1127         entry[ii]=NULL;
1128       } else {
1129         /* set metric to infinity and reset timer */
1130         tr_debug("trps_sweep_routes: setting metric to infinity and resetting expiry.");
1131         trp_route_set_metric(entry[ii], TRP_METRIC_INFINITY);
1132         trp_route_set_expiry(entry[ii], trps_compute_expiry(trps,
1133                                                              trp_route_get_interval(entry[ii]),
1134                                                              trp_route_get_expiry(entry[ii])));
1135       }
1136     }
1137   }
1138
1139   talloc_free(entry);
1140   return TRP_SUCCESS;
1141 }
1142
1143 /* add metrics */
1144 static unsigned int trps_metric_add(unsigned int m1, unsigned int m2)
1145 {
1146   if (trp_metric_is_invalid(m1) || trp_metric_is_invalid(m2))
1147     return TRP_METRIC_INVALID;
1148
1149   if (trp_metric_is_infinite(m1) || trp_metric_is_infinite(m2))
1150     return TRP_METRIC_INFINITY;
1151
1152   if (trp_metric_is_finite(m1+m2))
1153     return m1+m2;
1154   else
1155     return TRP_METRIC_INFINITY;
1156 }
1157
1158 /* convert an rentry into a new trp update info record */
1159 static TRP_INFOREC *trps_route_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
1160 {
1161   TRP_INFOREC *rec=trp_inforec_new(mem_ctx, TRP_INFOREC_TYPE_ROUTE);
1162   unsigned int linkcost=0;
1163
1164   if (rec!=NULL) {
1165     if (trp_route_is_local(route))
1166       linkcost=0;
1167     else {
1168       linkcost=trp_peer_get_linkcost(trps_get_peer_by_gssname(trps,
1169                                                               trp_route_get_peer(route)));
1170     }
1171
1172     /* Note that we leave the next hop empty since the recipient fills that in.
1173      * This is where we add the link cost (currently always 1) to the next peer. */
1174     if ((trp_inforec_set_trust_router(rec, trp_route_dup_trust_router(route)) != TRP_SUCCESS)
1175        ||(trp_inforec_set_metric(rec,
1176                                  trps_metric_add(trp_route_get_metric(route),
1177                                                  linkcost)) != TRP_SUCCESS)
1178        ||(trp_inforec_set_interval(rec, trps_get_update_interval(trps)) != TRP_SUCCESS)) {
1179       tr_err("trps_route_to_inforec: error creating route update.");
1180       talloc_free(rec);
1181       rec=NULL;
1182     }
1183   }
1184   return rec;
1185 }
1186
1187 static TRP_UPD *trps_route_to_upd(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
1188 {
1189   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1190   TRP_UPD *upd=trp_upd_new(tmp_ctx);
1191   TRP_INFOREC *rec=NULL;
1192
1193   if (upd==NULL) {
1194     tr_err("trps_route_to_upd: could not create update message.");
1195     goto cleanup;
1196   }
1197   trp_upd_set_realm(upd, trp_route_dup_realm(route));
1198   if (trp_upd_get_realm(upd)==NULL) {
1199     tr_err("trps_route_to_upd: could not copy realm.");
1200     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
1201     goto cleanup;
1202   }
1203   trp_upd_set_comm(upd, trp_route_dup_comm(route));
1204   if (trp_upd_get_comm(upd)==NULL) {
1205     tr_err("trps_route_to_upd: could not copy comm.");
1206     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
1207     goto cleanup;
1208   }
1209   rec=trps_route_to_inforec(tmp_ctx, trps, route);
1210   if (rec==NULL) {
1211     tr_err("trps_route_to_upd: could not create route info record for realm %.*s in comm %.*s.",
1212            trp_route_get_realm(route)->len, trp_route_get_realm(route)->buf,
1213            trp_route_get_comm(route)->len, trp_route_get_comm(route)->buf);
1214     upd=NULL; /* it's till in tmp_ctx, so it will be freed */
1215     goto cleanup;
1216   }
1217   trp_upd_add_inforec(upd, rec);
1218
1219   /* sucess */
1220   talloc_steal(mem_ctx, upd);
1221
1222 cleanup:
1223   talloc_free(tmp_ctx);
1224   return upd;
1225 }
1226
1227 /* select the correct route to comm/realm to be announced to peer */
1228 static TRP_ROUTE *trps_select_realm_update(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer_gssname)
1229 {
1230   TRP_ROUTE *route;
1231
1232   /* Take the currently selected route unless it is through the peer we're sending the update to.
1233    * I.e., enforce the split horizon rule. */
1234   route=trp_rtable_get_selected_entry(trps->rtable, comm, realm);
1235   if (route==NULL) {
1236     /* No selected route, this should only happen if the only route has been retracted,
1237      * in which case we do not want to advertise it. */
1238     return NULL;
1239   }
1240   tr_debug("trps_select_realm_update: %s vs %s", peer_gssname->buf,
1241            trp_route_get_peer(route)->buf);
1242   if (0==tr_name_cmp(peer_gssname, trp_route_get_peer(route))) {
1243     tr_debug("trps_select_realm_update: matched, finding alternate route");
1244     /* the selected entry goes through the peer we're reporting to, choose an alternate */
1245     route=trps_find_best_route(trps, comm, realm, peer_gssname);
1246     if ((route==NULL) || (!trp_metric_is_finite(trp_route_get_metric(route))))
1247       return NULL; /* don't advertise a nonexistent or retracted route */
1248   }
1249   return route;
1250 }
1251
1252 /* Add TRP_UPD msgs to the updates GPtrArray. Caller needs to arrange for these to be freed. */
1253 static TRP_RC trps_select_route_updates_for_peer(TALLOC_CTX *mem_ctx,
1254                                                  GPtrArray *updates,
1255                                                  TRPS_INSTANCE *trps,
1256                                                  TR_NAME *peer_gssname,
1257                                                  int triggered)
1258 {
1259   size_t n_comm=0;
1260   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
1261   TR_NAME **realm=NULL;
1262   size_t n_realm=0;
1263   size_t ii=0, jj=0;
1264   TRP_ROUTE *best=NULL;
1265   TRP_UPD *upd=NULL;
1266
1267   if (updates==NULL)
1268     return TRP_BADARG;
1269
1270   for (ii=0; ii<n_comm; ii++) {
1271     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
1272     for (jj=0; jj<n_realm; jj++) {
1273       best=trps_select_realm_update(trps, comm[ii], realm[jj], peer_gssname);
1274       /* If we found a route, add it to the list. If triggered!=0, then only
1275        * add triggered routes. */
1276       if ((best!=NULL) && ((!triggered) || trp_route_is_triggered(best))) {
1277         upd=trps_route_to_upd(mem_ctx, trps, best);
1278         if (upd==NULL) {
1279           tr_err("trps_select_route_updates_for_peer: unable to create update message.");
1280           continue;
1281         }
1282         g_ptr_array_add(updates, upd);
1283       }
1284     }
1285     
1286     if (realm!=NULL)
1287       talloc_free(realm);
1288     realm=NULL;
1289     n_realm=0;
1290   }
1291
1292   if (comm!=NULL)
1293     talloc_free(comm);
1294   
1295   return TRP_SUCCESS;
1296 }
1297
1298 static TRP_INFOREC *trps_memb_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_COMM_MEMB *memb)
1299 {
1300   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1301   TRP_INFOREC *rec=NULL;
1302   TR_COMM *comm=NULL;
1303
1304   if (memb==NULL)
1305     goto cleanup;
1306
1307   comm=tr_comm_memb_get_comm(memb);
1308   rec=trp_inforec_new(tmp_ctx, TRP_INFOREC_TYPE_COMMUNITY);
1309   if (rec==NULL)
1310     goto cleanup;
1311   
1312   if (TRP_SUCCESS!=trp_inforec_set_comm_type(rec, tr_comm_get_type(comm))) {
1313     rec=NULL;
1314     goto cleanup;
1315   }
1316   
1317   if (TRP_SUCCESS!=trp_inforec_set_role(rec, tr_comm_memb_get_role(memb))) {
1318     rec=NULL;
1319     goto cleanup;
1320   }
1321
1322   if ((NULL!=tr_comm_get_apcs(comm)) &&
1323       ( (TRP_SUCCESS!=trp_inforec_set_apcs(rec,
1324                                            tr_apc_dup(rec, tr_comm_get_apcs(comm)))) ||
1325         (NULL==trp_inforec_get_apcs(rec)))) {
1326     rec=NULL;
1327     goto cleanup;
1328   }
1329
1330   if ((NULL!=tr_comm_get_owner_realm(comm)) &&
1331       ( (TRP_SUCCESS!=trp_inforec_set_owner_realm(rec, tr_dup_name(tr_comm_get_owner_realm(comm)))) ||
1332         (NULL==trp_inforec_get_owner_realm(rec)))) {
1333     rec=NULL;
1334     goto cleanup;
1335   }
1336
1337   if ((NULL!=tr_comm_get_owner_contact(comm)) &&
1338       ( (TRP_SUCCESS!=trp_inforec_set_owner_contact(rec, tr_dup_name(tr_comm_get_owner_contact(comm)))) ||
1339         (NULL==trp_inforec_get_owner_contact(rec)))) {
1340     rec=NULL;
1341     goto cleanup;
1342   }
1343
1344   if ((NULL!=tr_comm_memb_get_provenance(memb)) &&
1345       (TRP_SUCCESS!=trp_inforec_set_provenance(rec, tr_comm_memb_get_provenance(memb)))) {
1346     rec=NULL;
1347     goto cleanup;
1348   }
1349
1350   if (TRP_SUCCESS!=trp_inforec_set_interval(rec, tr_comm_memb_get_interval(memb))) {
1351     rec=NULL;
1352     goto cleanup;
1353   }
1354
1355   /* success! */
1356   talloc_steal(mem_ctx, rec);
1357
1358 cleanup:
1359   talloc_free(tmp_ctx);
1360   return rec;
1361 }
1362
1363 /* construct an update with all the inforecs for comm/realm/role to be sent to peer */
1364 static TRP_UPD *trps_comm_update(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_NAME *peer_gssname, TR_COMM *comm, TR_REALM *realm)
1365 {
1366   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1367   TRP_UPD *upd=trp_upd_new(tmp_ctx);
1368   TRP_INFOREC *rec=NULL;
1369   TR_COMM_ITER *iter=NULL;
1370   TR_COMM_MEMB *memb=NULL;
1371
1372   if (upd==NULL)
1373     goto cleanup;
1374   
1375   trp_upd_set_comm(upd, tr_comm_dup_id(comm));
1376   trp_upd_set_realm(upd, tr_realm_dup_id(realm));
1377   /* leave peer empty */
1378
1379   iter=tr_comm_iter_new(tmp_ctx);
1380   if (iter==NULL) {
1381     tr_err("trps_comm_update: unable to allocate iterator.");
1382     upd=NULL;
1383     goto cleanup;
1384   }
1385   
1386   /* now add inforecs */
1387   switch (realm->role) {
1388   case TR_ROLE_IDP:
1389     memb=tr_comm_table_find_idp_memb(trps->ctable,
1390                                      tr_realm_get_id(realm),
1391                                      tr_comm_get_id(comm));
1392     break;
1393   case TR_ROLE_RP:
1394     memb=tr_comm_table_find_rp_memb(trps->ctable,
1395                                     tr_realm_get_id(realm),
1396                                     tr_comm_get_id(comm));
1397     break;
1398   default:
1399     break;
1400   }
1401   if (memb!=NULL) {
1402     for (memb=tr_comm_memb_iter_first(iter, memb);
1403          memb!=NULL;
1404          memb=tr_comm_memb_iter_next(iter)) {
1405       rec=trps_memb_to_inforec(tmp_ctx, trps, memb);
1406       if (rec==NULL) {
1407         tr_err("trps_comm_update: unable to allocate inforec.");
1408         upd=NULL;
1409         goto cleanup;
1410       }
1411       trp_upd_add_inforec(upd, rec);
1412     }
1413   }
1414
1415   if (trp_upd_get_inforec(upd)==NULL)
1416     upd=NULL; /* no inforecs, no reason to send the update */
1417   else
1418     talloc_steal(mem_ctx, upd); /* success! */
1419
1420 cleanup:
1421   talloc_free(tmp_ctx);
1422   return upd;
1423 }
1424
1425 /* Find all community updates to send to a peer and add these as TR_UPD records
1426  * to the updates GPtrArray. */
1427 static TRP_RC trps_select_comm_updates_for_peer(TALLOC_CTX *mem_ctx,
1428                                                 GPtrArray *updates,
1429                                                 TRPS_INSTANCE *trps,
1430                                                 TR_NAME *peer_gssname,
1431                                                 int triggered)
1432 {
1433   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1434   TR_COMM_ITER *comm_iter=NULL;
1435   TR_COMM *comm=NULL;
1436   TR_COMM_ITER *realm_iter=NULL;
1437   TR_REALM *realm=NULL;
1438   TRP_UPD *upd=NULL;
1439   TRP_RC rc=TRP_ERROR;
1440
1441   /* currently do not send any communities on triggered updates */
1442   if (triggered) {
1443     rc=TRP_SUCCESS;
1444     goto cleanup;
1445   }
1446
1447   comm_iter=tr_comm_iter_new(tmp_ctx);
1448   realm_iter=tr_comm_iter_new(tmp_ctx);
1449   if ((comm_iter==NULL) || (realm_iter==NULL)) {
1450     tr_err("trps_select_comm_updates_for_peer: unable to allocate iterator.");
1451     rc=TRP_NOMEM;
1452     goto cleanup;
1453   }
1454
1455   /* do every community */
1456   for (comm=tr_comm_table_iter_first(comm_iter, trps->ctable);
1457        comm!=NULL;
1458        comm=tr_comm_table_iter_next(comm_iter)) {
1459     /* do every realm in this community */
1460     tr_debug("trps_select_comm_updates_for_peer: looking through community %.*s",
1461              tr_comm_get_id(comm)->len,
1462              tr_comm_get_id(comm)->buf);
1463     for (realm=tr_realm_iter_first(realm_iter, trps->ctable, tr_comm_get_id(comm));
1464          realm!=NULL;
1465          realm=tr_realm_iter_next(realm_iter)) {
1466       /* get the update for this comm/realm */
1467       tr_debug("trps_select_comm_updates_for_peer: adding realm %.*s",
1468                tr_realm_get_id(realm)->len,
1469                tr_realm_get_id(realm)->buf);
1470       upd=trps_comm_update(mem_ctx, trps, peer_gssname, comm, realm);
1471       if (upd!=NULL)
1472         g_ptr_array_add(updates, upd);
1473     }
1474   }
1475
1476 cleanup:
1477   talloc_free(tmp_ctx);
1478   return rc;
1479 }
1480
1481
1482 /* helper for trps_update_one_peer. Frees the TRP_UPD pointed to by a GPtrArray element */
1483 static void trps_trp_upd_destroy(gpointer data)
1484 {
1485   trp_upd_free((TRP_UPD *)data);
1486 }
1487
1488 /* all routes/communities to a single peer, unless comm/realm are specified (both or neither must be NULL) */
1489 static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
1490                                    TRP_PEER *peer,
1491                                    TRP_UPDATE_TYPE update_type,
1492                                    TR_NAME *comm,
1493                                    TR_NAME *realm)
1494 {
1495   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1496   TR_MSG msg; /* not a pointer! */
1497   TRP_UPD *upd=NULL;
1498   TRP_ROUTE *route=NULL;
1499   size_t ii=0;
1500   char *encoded=NULL;
1501   TRP_RC rc=TRP_ERROR;
1502   TR_NAME *peer_label=trp_peer_get_label(peer);
1503   GPtrArray *updates=g_ptr_array_new_with_free_func(trps_trp_upd_destroy);
1504
1505   if (updates==NULL) {
1506     tr_err("trps_update_one_peer: unable to allocate updates array.");
1507     rc=TRP_NOMEM;
1508     goto cleanup;
1509   }
1510
1511   switch (update_type) {
1512   case TRP_UPDATE_TRIGGERED:
1513     tr_debug("trps_update_one_peer: preparing triggered update for %.*s",
1514              peer_label->len, peer_label->buf);
1515     break;
1516   case TRP_UPDATE_SCHEDULED:
1517     tr_debug("trps_update_one_peer: preparing scheduled update for %.*s",
1518              peer_label->len, peer_label->buf);
1519     break;
1520   case TRP_UPDATE_REQUESTED:
1521     tr_debug("trps_update_one_peer: preparing requested update for %.*s",
1522              peer_label->len, peer_label->buf);
1523     break;
1524   default:
1525     tr_err("trps_update_one_peer: invalid update type requested.");
1526     rc=TRP_BADARG;
1527     goto cleanup;
1528   }
1529
1530   /* First, gather route updates. */
1531   tr_debug("trps_update_one_peer: selecting route updates for %.*s.", peer_label->len, peer_label->buf);
1532   if ((comm==NULL) && (realm==NULL)) {
1533     /* do all realms */
1534     rc=trps_select_route_updates_for_peer(tmp_ctx,
1535                                           updates,
1536                                           trps,
1537                                           peer_label,
1538                                           update_type==TRP_UPDATE_TRIGGERED);
1539   } else if ((comm!=NULL) && (realm!=NULL)) {
1540     /* a single community/realm was requested */
1541     route=trps_select_realm_update(trps, comm, realm, peer_label);
1542     if (route==NULL) {
1543       /* we have no actual update to send back, MUST send a retraction */
1544       tr_debug("trps_update_one_peer: community/realm without route requested, sending mandatory retraction.");
1545       route=trp_route_new(tmp_ctx);
1546       trp_route_set_comm(route, tr_dup_name(comm));
1547       trp_route_set_realm(route, tr_dup_name(realm));
1548       trp_route_set_peer(route, tr_new_name(""));
1549       trp_route_set_metric(route, TRP_METRIC_INFINITY);
1550       trp_route_set_trust_router(route, tr_new_name(""));
1551       trp_route_set_next_hop(route, tr_new_name(""));
1552     }
1553     upd=trps_route_to_upd(tmp_ctx, trps, route);
1554     if (upd==NULL) {
1555       tr_err("trps_update_one_peer: unable to allocate route update.");
1556       rc=TRP_NOMEM;
1557       goto cleanup;
1558     }
1559     g_ptr_array_add(updates, upd);
1560   } else {
1561     tr_err("trps_update_one_peer: error: only comm or realm was specified. Need both or neither.");
1562     rc=TRP_ERROR;
1563     goto cleanup;
1564   }
1565
1566   /* Second, gather community updates */
1567   tr_debug("trps_update_one_peer: selecting community updates for %.*s.", peer_label->len, peer_label->buf);
1568   rc=trps_select_comm_updates_for_peer(tmp_ctx, updates, trps, peer_label, update_type==TRP_UPDATE_TRIGGERED);
1569
1570   /* see if we have anything to send */
1571   if (updates->len<=0)
1572     tr_debug("trps_update_one_peer: no updates for %.*s", peer_label->len, peer_label->buf);
1573   else {
1574     tr_debug("trps_update_one_peer: sending %d update messages.", updates->len);
1575     for (ii=0; ii<updates->len; ii++) {
1576       upd=(TRP_UPD *)g_ptr_array_index(updates, ii);
1577       /* now encode the update message */
1578       tr_msg_set_trp_upd(&msg, upd);
1579       encoded=tr_msg_encode(&msg);
1580       if (encoded==NULL) {
1581         tr_err("trps_update_one_peer: error encoding update.");
1582         rc=TRP_ERROR;
1583         goto cleanup;
1584       }
1585
1586       tr_debug("trps_update_one_peer: adding message to queue.");
1587       if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
1588         tr_err("trps_update_one_peer: error queueing update.");
1589       else
1590         tr_debug("trps_update_one_peer: update queued successfully.");
1591
1592       tr_msg_free_encoded(encoded);
1593       encoded=NULL;
1594     }
1595   }
1596
1597   rc=TRP_SUCCESS;
1598
1599 cleanup:
1600   if (updates!=NULL)
1601     g_ptr_array_free(updates, TRUE); /* frees any TRP_UPD records */
1602   talloc_free(tmp_ctx);
1603   return rc;
1604 }
1605
1606 /* all routes/communities to all peers */
1607 TRP_RC trps_update(TRPS_INSTANCE *trps, TRP_UPDATE_TYPE update_type)
1608 {
1609   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1610   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
1611   TRP_PEER *peer=NULL;
1612   TRP_RC rc=TRP_SUCCESS;
1613
1614   if (trps->ptable==NULL)
1615     return TRP_SUCCESS; /* no peers, nothing to do */
1616
1617   if (iter==NULL) {
1618     tr_err("trps_update: failed to allocate peer table iterator.");
1619     talloc_free(tmp_ctx);
1620     return TRP_NOMEM;
1621   }
1622
1623   for (peer=trp_ptable_iter_first(iter, trps->ptable);
1624        (peer!=NULL) && (rc==TRP_SUCCESS);
1625        peer=trp_ptable_iter_next(iter))
1626   {
1627     if (!trps_peer_connected(trps, peer)) {
1628       TR_NAME *peer_label=trp_peer_get_label(peer);
1629       tr_debug("trps_update: no TRP connection to %.*s, skipping.",
1630                peer_label->len, peer_label->buf);
1631       continue;
1632     }
1633     rc=trps_update_one_peer(trps, peer, update_type, NULL, NULL);
1634   }
1635
1636   tr_debug("trps_update: rc=%u after attempting update.", rc);
1637   trp_ptable_iter_free(iter);
1638   trp_rtable_clear_triggered(trps->rtable); /* don't re-send triggered updates */
1639   talloc_free(tmp_ctx);
1640   return rc;
1641 }        
1642
1643 TRP_RC trps_add_route(TRPS_INSTANCE *trps, TRP_ROUTE *route)
1644 {
1645   trp_rtable_add(trps->rtable, route); /* should return status */
1646   return TRP_SUCCESS; 
1647 }
1648
1649 /* steals the peer object */
1650 TRP_RC trps_add_peer(TRPS_INSTANCE *trps, TRP_PEER *peer)
1651 {
1652   if (trps->ptable==NULL) {
1653     trps->ptable=trp_ptable_new(trps);
1654     if (trps->ptable==NULL)
1655       return TRP_NOMEM;
1656   }
1657   return trp_ptable_add(trps->ptable, peer);
1658 }
1659
1660 TRP_PEER *trps_get_peer_by_gssname(TRPS_INSTANCE *trps, TR_NAME *gssname)
1661 {
1662   if (trps->ptable==NULL)
1663     return NULL;
1664
1665   return trp_ptable_find_gss_name(trps->ptable, gssname);
1666 }
1667
1668 TRP_PEER *trps_get_peer_by_servicename(TRPS_INSTANCE *trps, TR_NAME *servicename)
1669 {
1670   if (trps->ptable==NULL)
1671     return NULL;
1672
1673   return trp_ptable_find_servicename(trps->ptable, servicename);
1674 }
1675
1676 int trps_peer_connected(TRPS_INSTANCE *trps, TRP_PEER *peer)
1677 {
1678   TRPC_INSTANCE *trpc=trps_find_trpc(trps, peer);
1679   if (trpc==NULL)
1680     return 0;
1681
1682   if (trpc_get_status(trpc)==TRP_CONNECTION_UP)
1683     return 1;
1684   else
1685     return 0;
1686 }
1687
1688
1689 static TRP_RC trps_handle_request(TRPS_INSTANCE *trps, TRP_REQ *req)
1690 {
1691   TR_NAME *comm=NULL;
1692   TR_NAME *realm=NULL;
1693
1694   tr_debug("trps_handle_request: handling TRP request.");
1695
1696   if (trps_validate_request(trps, req) != TRP_SUCCESS) {
1697     tr_notice("trps_handle_request: received invalid TRP request.");
1698     return TRP_ERROR;
1699   }
1700
1701   if (!trp_req_is_wildcard(req)) {
1702     comm=trp_req_get_comm(req);
1703     realm=trp_req_get_realm(req);
1704     tr_debug("trps_handle_request: route for %.*s/%.*s requested.",
1705              comm->len, comm->buf, realm->len, realm->buf);
1706   } else {
1707     tr_debug("trps_handle_request: all routes requested.");
1708     /* leave comm/realm NULL */
1709   }
1710   return trps_update_one_peer(trps,
1711                               trps_get_peer_by_gssname(trps, trp_req_get_peer(req)),
1712                               TRP_UPDATE_REQUESTED,
1713                               comm,
1714                               realm);
1715 }
1716
1717
1718 TRP_RC trps_handle_tr_msg(TRPS_INSTANCE *trps, TR_MSG *tr_msg)
1719 {
1720   TRP_RC rc=TRP_ERROR;
1721
1722   switch (tr_msg_get_msg_type(tr_msg)) {
1723   case TRP_UPDATE:
1724     rc=trps_handle_update(trps, tr_msg_get_trp_upd(tr_msg));
1725     if (rc==TRP_SUCCESS) {
1726       rc=trps_update_active_routes(trps);
1727       trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
1728     }
1729     return rc;
1730
1731   case TRP_REQUEST:
1732     rc=trps_handle_request(trps, tr_msg_get_trp_req(tr_msg));
1733     return rc;
1734
1735   default:
1736     /* unknown error or one we don't care about (e.g., TID messages) */
1737     return TRP_ERROR;
1738   }
1739 }
1740
1741 /* send wildcard route request to a peer */
1742 TRP_RC trps_wildcard_route_req(TRPS_INSTANCE *trps, TR_NAME *peer_servicename)
1743 {
1744   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1745   TRP_PEER *peer=trps_get_peer_by_servicename(trps, peer_servicename);
1746   TR_MSG msg; /* not a pointer */
1747   TRP_REQ *req=trp_req_new(tmp_ctx);
1748   char *encoded=NULL;
1749   TRP_RC rc=TRP_ERROR;
1750
1751   if (peer==NULL) {
1752     tr_err("trps_wildcard_route_req: unknown peer (%.*s).", peer_servicename->len, peer_servicename->buf);
1753     rc=TRP_BADARG;
1754     goto cleanup;
1755   }
1756   if ((req==NULL) || (trp_req_make_wildcard(req)!=TRP_SUCCESS)) {
1757     tr_err("trps_wildcard_route_req: unable to create wildcard TRP request.");
1758     rc=TRP_NOMEM;
1759     goto cleanup;
1760   }
1761
1762   tr_msg_set_trp_req(&msg, req);
1763   encoded=tr_msg_encode(&msg);
1764   if (encoded==NULL) {
1765     tr_err("trps_wildcard_route_req: error encoding wildcard TRP request.");
1766     rc=TRP_ERROR;
1767     goto cleanup;
1768   }
1769
1770   tr_debug("trps_wildcard_route_req: adding message to queue.");
1771   if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS) {
1772     tr_err("trps_wildcard_route_req: error queueing request.");
1773     rc=TRP_ERROR;
1774   } else {
1775     tr_debug("trps_wildcard_route_req: request queued successfully.");
1776     rc=TRP_SUCCESS;
1777   }
1778
1779 cleanup:
1780   if (encoded!=NULL)
1781     tr_msg_free_encoded(encoded);
1782   if (req!=NULL)
1783     trp_req_free(req);
1784
1785   talloc_free(tmp_ctx);
1786   return rc;
1787 }