Handle community updates when received. Builds, not tested.
[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       if (TRP_SUCCESS!=trps_handle_inforec_route(trps, upd, rec))
977         tr_notice("trps_handle_update: error handling route inforec.");
978       break;
979     case TRP_INFOREC_TYPE_COMMUNITY:
980       if (TRP_SUCCESS!=trps_handle_inforec_comm(trps, upd, rec))
981         tr_notice("trps_handle_update: error handling community inforec.");
982       break;
983     default:
984       tr_notice("trps_handle_update: unsupported inforec in TRP update.");
985       break;
986     }
987   }
988   return TRP_SUCCESS;
989 }
990
991 static TRP_RC trps_validate_request(TRPS_INSTANCE *trps, TRP_REQ *req)
992 {
993   if (req==NULL) {
994     tr_notice("trps_validate_request: null TRP request.");
995     return TRP_BADARG;
996   }
997
998   if (trp_req_get_comm(req)==NULL) {
999     tr_notice("trps_validate_request: received TRP request with null community.");
1000     return TRP_ERROR;
1001   }
1002   
1003   if (trp_req_get_realm(req)==NULL) {
1004     tr_notice("trps_validate_request: received TRP request with null realm.");
1005     return TRP_ERROR;
1006   }
1007   
1008   if (trp_req_get_peer(req)==NULL) {
1009     tr_notice("trps_validate_request: received TRP request without origin peer information.");
1010     return TRP_ERROR;
1011   }
1012   
1013   return TRP_SUCCESS;
1014 }
1015
1016 /* choose the best route to comm/realm, optionally excluding routes to a particular peer */
1017 static TRP_ROUTE *trps_find_best_route(TRPS_INSTANCE *trps,
1018                                         TR_NAME *comm,
1019                                         TR_NAME *realm,
1020                                         TR_NAME *exclude_peer)
1021 {
1022   TRP_ROUTE **entry=NULL;
1023   TRP_ROUTE *best=NULL;
1024   size_t n_entry=0;
1025   unsigned int kk=0;
1026   unsigned int kk_min=0;
1027   unsigned int min_metric=TRP_METRIC_INFINITY;
1028
1029   entry=trp_rtable_get_realm_entries(trps->rtable, comm, realm, &n_entry);
1030   for (kk=0; kk<n_entry; kk++) {
1031     if (trp_route_get_metric(entry[kk]) < min_metric) {
1032       if ((exclude_peer==NULL) || (0!=tr_name_cmp(trp_route_get_peer(entry[kk]),
1033                                                   exclude_peer))) {
1034         kk_min=kk;
1035         min_metric=trp_route_get_metric(entry[kk]);
1036       } 
1037     }
1038   }
1039   if (trp_metric_is_finite(min_metric))
1040     best=entry[kk_min];
1041   
1042   talloc_free(entry);
1043   return best;
1044 }
1045
1046 /* TODO: think this through more carefully. At least ought to add hysteresis
1047  * to avoid flapping between routers or routes. */
1048 TRP_RC trps_update_active_routes(TRPS_INSTANCE *trps)
1049 {
1050   size_t n_comm=0, ii=0;
1051   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
1052   size_t n_realm=0, jj=0;
1053   TR_NAME **realm=NULL;
1054   TRP_ROUTE *best_route=NULL, *cur_route=NULL;
1055   unsigned int best_metric=0, cur_metric=0;
1056
1057   for (ii=0; ii<n_comm; ii++) {
1058     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
1059     for (jj=0; jj<n_realm; jj++) {
1060       best_route=trps_find_best_route(trps, comm[ii], realm[jj], NULL);
1061       if (best_route==NULL)
1062         best_metric=TRP_METRIC_INFINITY;
1063       else
1064         best_metric=trp_route_get_metric(best_route);
1065
1066       cur_route=trps_get_selected_route(trps, comm[ii], realm[jj]);
1067       if (cur_route!=NULL) {
1068         cur_metric=trp_route_get_metric(cur_route);
1069         if ((best_metric < cur_metric) && (trp_metric_is_finite(best_metric))) {
1070           /* The new route has a lower metric than the previous, and is finite. Accept. */
1071           trp_route_set_selected(cur_route, 0);
1072           trp_route_set_selected(best_route, 1);
1073         } else if (!trp_metric_is_finite(cur_metric)) /* rejects infinite or invalid metrics */
1074           trp_route_set_selected(cur_route, 0);
1075       } else if (trp_metric_is_finite(best_metric)) {
1076         trp_route_set_selected(best_route, 1);
1077       }
1078     }
1079     if (realm!=NULL)
1080       talloc_free(realm);
1081     realm=NULL; n_realm=0;
1082   }
1083   if (comm!=NULL)
1084     talloc_free(comm);
1085   comm=NULL; n_comm=0;
1086
1087   return TRP_SUCCESS;
1088 }
1089
1090 /* true if curtime >= expiry */
1091 static int trps_expired(struct timespec *expiry, struct timespec *curtime)
1092 {
1093   return ((curtime->tv_sec > expiry->tv_sec)
1094          || ((curtime->tv_sec == expiry->tv_sec)
1095             &&(curtime->tv_nsec >= expiry->tv_nsec)));
1096 }
1097
1098 /* Sweep for expired routes. For each expired route, if its metric is infinite, the route is flushed.
1099  * If its metric is finite, the metric is set to infinite and the route's expiration time is updated. */
1100 TRP_RC trps_sweep_routes(TRPS_INSTANCE *trps)
1101 {
1102   struct timespec sweep_time={0,0};
1103   TRP_ROUTE **entry=NULL;
1104   size_t n_entry=0;
1105   size_t ii=0;
1106
1107   /* use a single time for the entire sweep */
1108   if (0!=clock_gettime(CLOCK_REALTIME, &sweep_time)) {
1109     tr_err("trps_sweep_routes: could not read realtime clock.");
1110     sweep_time.tv_sec=0;
1111     sweep_time.tv_nsec=0;
1112     return TRP_ERROR;
1113   }
1114
1115   entry=trp_rtable_get_entries(trps->rtable, &n_entry); /* must talloc_free *entry */
1116
1117   /* loop over the entries */
1118   for (ii=0; ii<n_entry; ii++) {
1119     if (!trp_route_is_local(entry[ii]) && trps_expired(trp_route_get_expiry(entry[ii]), &sweep_time)) {
1120       tr_debug("trps_sweep_routes: route expired.");
1121       if (!trp_metric_is_finite(trp_route_get_metric(entry[ii]))) {
1122         /* flush route */
1123         tr_debug("trps_sweep_routes: metric was infinity, flushing route.");
1124         trp_rtable_remove(trps->rtable, entry[ii]); /* entry[ii] is no longer valid */
1125         entry[ii]=NULL;
1126       } else {
1127         /* set metric to infinity and reset timer */
1128         tr_debug("trps_sweep_routes: setting metric to infinity and resetting expiry.");
1129         trp_route_set_metric(entry[ii], TRP_METRIC_INFINITY);
1130         trp_route_set_expiry(entry[ii], trps_compute_expiry(trps,
1131                                                              trp_route_get_interval(entry[ii]),
1132                                                              trp_route_get_expiry(entry[ii])));
1133       }
1134     }
1135   }
1136
1137   talloc_free(entry);
1138   return TRP_SUCCESS;
1139 }
1140
1141 /* add metrics */
1142 static unsigned int trps_metric_add(unsigned int m1, unsigned int m2)
1143 {
1144   if (trp_metric_is_invalid(m1) || trp_metric_is_invalid(m2))
1145     return TRP_METRIC_INVALID;
1146
1147   if (trp_metric_is_infinite(m1) || trp_metric_is_infinite(m2))
1148     return TRP_METRIC_INFINITY;
1149
1150   if (trp_metric_is_finite(m1+m2))
1151     return m1+m2;
1152   else
1153     return TRP_METRIC_INFINITY;
1154 }
1155
1156 /* convert an rentry into a new trp update info record */
1157 static TRP_INFOREC *trps_route_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
1158 {
1159   TRP_INFOREC *rec=trp_inforec_new(mem_ctx, TRP_INFOREC_TYPE_ROUTE);
1160   unsigned int linkcost=0;
1161
1162   if (rec!=NULL) {
1163     if (trp_route_is_local(route))
1164       linkcost=0;
1165     else {
1166       linkcost=trp_peer_get_linkcost(trps_get_peer_by_gssname(trps,
1167                                                               trp_route_get_peer(route)));
1168     }
1169
1170     /* Note that we leave the next hop empty since the recipient fills that in.
1171      * This is where we add the link cost (currently always 1) to the next peer. */
1172     if ((trp_inforec_set_trust_router(rec, trp_route_dup_trust_router(route)) != TRP_SUCCESS)
1173        ||(trp_inforec_set_metric(rec,
1174                                  trps_metric_add(trp_route_get_metric(route),
1175                                                  linkcost)) != TRP_SUCCESS)
1176        ||(trp_inforec_set_interval(rec, trps_get_update_interval(trps)) != TRP_SUCCESS)) {
1177       tr_err("trps_route_to_inforec: error creating route update.");
1178       talloc_free(rec);
1179       rec=NULL;
1180     }
1181   }
1182   return rec;
1183 }
1184
1185 static TRP_UPD *trps_route_to_upd(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TRP_ROUTE *route)
1186 {
1187   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1188   TRP_UPD *upd=trp_upd_new(tmp_ctx);
1189   TRP_INFOREC *rec=NULL;
1190
1191   if (upd==NULL) {
1192     tr_err("trps_route_to_upd: could not create update message.");
1193     goto cleanup;
1194   }
1195   trp_upd_set_realm(upd, trp_route_dup_realm(route));
1196   if (trp_upd_get_realm(upd)==NULL) {
1197     tr_err("trps_route_to_upd: could not copy realm.");
1198     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
1199     goto cleanup;
1200   }
1201   trp_upd_set_comm(upd, trp_route_dup_comm(route));
1202   if (trp_upd_get_comm(upd)==NULL) {
1203     tr_err("trps_route_to_upd: could not copy comm.");
1204     upd=NULL; /* it's still in tmp_ctx, so it will be freed */
1205     goto cleanup;
1206   }
1207   rec=trps_route_to_inforec(tmp_ctx, trps, route);
1208   if (rec==NULL) {
1209     tr_err("trps_route_to_upd: could not create route info record for realm %.*s in comm %.*s.",
1210            trp_route_get_realm(route)->len, trp_route_get_realm(route)->buf,
1211            trp_route_get_comm(route)->len, trp_route_get_comm(route)->buf);
1212     upd=NULL; /* it's till in tmp_ctx, so it will be freed */
1213     goto cleanup;
1214   }
1215   trp_upd_add_inforec(upd, rec);
1216
1217   /* sucess */
1218   talloc_steal(mem_ctx, upd);
1219
1220 cleanup:
1221   talloc_free(tmp_ctx);
1222   return upd;
1223 }
1224
1225 /* select the correct route to comm/realm to be announced to peer */
1226 static TRP_ROUTE *trps_select_realm_update(TRPS_INSTANCE *trps, TR_NAME *comm, TR_NAME *realm, TR_NAME *peer_gssname)
1227 {
1228   TRP_ROUTE *route;
1229
1230   /* Take the currently selected route unless it is through the peer we're sending the update to.
1231    * I.e., enforce the split horizon rule. */
1232   route=trp_rtable_get_selected_entry(trps->rtable, comm, realm);
1233   if (route==NULL) {
1234     /* No selected route, this should only happen if the only route has been retracted,
1235      * in which case we do not want to advertise it. */
1236     return NULL;
1237   }
1238   tr_debug("trps_select_realm_update: %s vs %s", peer_gssname->buf,
1239            trp_route_get_peer(route)->buf);
1240   if (0==tr_name_cmp(peer_gssname, trp_route_get_peer(route))) {
1241     tr_debug("trps_select_realm_update: matched, finding alternate route");
1242     /* the selected entry goes through the peer we're reporting to, choose an alternate */
1243     route=trps_find_best_route(trps, comm, realm, peer_gssname);
1244     if ((route==NULL) || (!trp_metric_is_finite(trp_route_get_metric(route))))
1245       return NULL; /* don't advertise a nonexistent or retracted route */
1246   }
1247   return route;
1248 }
1249
1250 /* Add TRP_UPD msgs to the updates GPtrArray. Caller needs to arrange for these to be freed. */
1251 static TRP_RC trps_select_route_updates_for_peer(TALLOC_CTX *mem_ctx,
1252                                                  GPtrArray *updates,
1253                                                  TRPS_INSTANCE *trps,
1254                                                  TR_NAME *peer_gssname,
1255                                                  int triggered)
1256 {
1257   size_t n_comm=0;
1258   TR_NAME **comm=trp_rtable_get_comms(trps->rtable, &n_comm);
1259   TR_NAME **realm=NULL;
1260   size_t n_realm=0;
1261   size_t ii=0, jj=0;
1262   TRP_ROUTE *best=NULL;
1263   TRP_UPD *upd=NULL;
1264
1265   if (updates==NULL)
1266     return TRP_BADARG;
1267
1268   for (ii=0; ii<n_comm; ii++) {
1269     realm=trp_rtable_get_comm_realms(trps->rtable, comm[ii], &n_realm);
1270     for (jj=0; jj<n_realm; jj++) {
1271       best=trps_select_realm_update(trps, comm[ii], realm[jj], peer_gssname);
1272       /* If we found a route, add it to the list. If triggered!=0, then only
1273        * add triggered routes. */
1274       if ((best!=NULL) && ((!triggered) || trp_route_is_triggered(best))) {
1275         upd=trps_route_to_upd(mem_ctx, trps, best);
1276         if (upd==NULL) {
1277           tr_err("trps_select_route_updates_for_peer: unable to create update message.");
1278           continue;
1279         }
1280         g_ptr_array_add(updates, upd);
1281       }
1282     }
1283     
1284     if (realm!=NULL)
1285       talloc_free(realm);
1286     realm=NULL;
1287     n_realm=0;
1288   }
1289
1290   if (comm!=NULL)
1291     talloc_free(comm);
1292   
1293   return TRP_SUCCESS;
1294 }
1295
1296 static TRP_INFOREC *trps_memb_to_inforec(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_COMM_MEMB *memb)
1297 {
1298   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1299   TRP_INFOREC *rec=NULL;
1300   TR_COMM *comm=NULL;
1301
1302   if (memb==NULL)
1303     goto cleanup;
1304
1305   comm=tr_comm_memb_get_comm(memb);
1306   rec=trp_inforec_new(tmp_ctx, TRP_INFOREC_TYPE_COMMUNITY);
1307   if (rec==NULL)
1308     goto cleanup;
1309   
1310   if (TRP_SUCCESS!=trp_inforec_set_comm_type(rec, tr_comm_get_type(comm))) {
1311     rec=NULL;
1312     goto cleanup;
1313   }
1314   
1315   if (TRP_SUCCESS!=trp_inforec_set_role(rec, tr_comm_memb_get_role(memb))) {
1316     rec=NULL;
1317     goto cleanup;
1318   }
1319
1320   if ((NULL!=tr_comm_get_apcs(comm)) &&
1321       ( (TRP_SUCCESS!=trp_inforec_set_apcs(rec,
1322                                            tr_apc_dup(rec, tr_comm_get_apcs(comm)))) ||
1323         (NULL==trp_inforec_get_apcs(rec)))) {
1324     rec=NULL;
1325     goto cleanup;
1326   }
1327
1328   if ((NULL!=tr_comm_get_owner_realm(comm)) &&
1329       ( (TRP_SUCCESS!=trp_inforec_set_owner_realm(rec, tr_dup_name(tr_comm_get_owner_realm(comm)))) ||
1330         (NULL==trp_inforec_get_owner_realm(rec)))) {
1331     rec=NULL;
1332     goto cleanup;
1333   }
1334
1335   if ((NULL!=tr_comm_get_owner_contact(comm)) &&
1336       ( (TRP_SUCCESS!=trp_inforec_set_owner_contact(rec, tr_dup_name(tr_comm_get_owner_contact(comm)))) ||
1337         (NULL==trp_inforec_get_owner_contact(rec)))) {
1338     rec=NULL;
1339     goto cleanup;
1340   }
1341
1342   if ((NULL!=tr_comm_memb_get_provenance(memb)) &&
1343       (TRP_SUCCESS!=trp_inforec_set_provenance(rec, tr_comm_memb_get_provenance(memb)))) {
1344     rec=NULL;
1345     goto cleanup;
1346   }
1347
1348   if (TRP_SUCCESS!=trp_inforec_set_interval(rec, tr_comm_memb_get_interval(memb))) {
1349     rec=NULL;
1350     goto cleanup;
1351   }
1352
1353   /* success! */
1354   talloc_steal(mem_ctx, rec);
1355
1356 cleanup:
1357   talloc_free(tmp_ctx);
1358   return rec;
1359 }
1360
1361 /* construct an update with all the inforecs for comm/realm/role to be sent to peer */
1362 static TRP_UPD *trps_comm_update(TALLOC_CTX *mem_ctx, TRPS_INSTANCE *trps, TR_NAME *peer_gssname, TR_COMM *comm, TR_REALM *realm)
1363 {
1364   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1365   TRP_UPD *upd=trp_upd_new(tmp_ctx);
1366   TRP_INFOREC *rec=NULL;
1367   TR_COMM_ITER *iter=NULL;
1368   TR_COMM_MEMB *memb=NULL;
1369
1370   if (upd==NULL)
1371     goto cleanup;
1372   
1373   trp_upd_set_comm(upd, tr_comm_dup_id(comm));
1374   trp_upd_set_realm(upd, tr_realm_dup_id(realm));
1375   /* leave peer empty */
1376
1377   iter=tr_comm_iter_new(tmp_ctx);
1378   if (iter==NULL) {
1379     tr_err("trps_comm_update: unable to allocate iterator.");
1380     upd=NULL;
1381     goto cleanup;
1382   }
1383   
1384   /* now add inforecs */
1385   switch (realm->role) {
1386   case TR_ROLE_IDP:
1387     memb=tr_comm_table_find_idp_memb(trps->ctable,
1388                                      tr_realm_get_id(realm),
1389                                      tr_comm_get_id(comm));
1390     break;
1391   case TR_ROLE_RP:
1392     memb=tr_comm_table_find_rp_memb(trps->ctable,
1393                                     tr_realm_get_id(realm),
1394                                     tr_comm_get_id(comm));
1395     break;
1396   default:
1397     break;
1398   }
1399   if (memb!=NULL) {
1400     for (memb=tr_comm_memb_iter_first(iter, memb);
1401          memb!=NULL;
1402          memb=tr_comm_memb_iter_next(iter)) {
1403       rec=trps_memb_to_inforec(tmp_ctx, trps, memb);
1404       if (rec==NULL) {
1405         tr_err("trps_comm_update: unable to allocate inforec.");
1406         upd=NULL;
1407         goto cleanup;
1408       }
1409       trp_upd_add_inforec(upd, rec);
1410     }
1411   }
1412
1413   if (trp_upd_get_inforec(upd)==NULL)
1414     upd=NULL; /* no inforecs, no reason to send the update */
1415   else
1416     talloc_steal(mem_ctx, upd); /* success! */
1417
1418 cleanup:
1419   talloc_free(tmp_ctx);
1420   return upd;
1421 }
1422
1423 /* Find all community updates to send to a peer and add these as TR_UPD records
1424  * to the updates GPtrArray. */
1425 static TRP_RC trps_select_comm_updates_for_peer(TALLOC_CTX *mem_ctx, GPtrArray *updates, TRPS_INSTANCE *trps, TR_NAME *peer_gssname)
1426 {
1427   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1428   TR_COMM_ITER *comm_iter=NULL;
1429   TR_COMM *comm=NULL;
1430   TR_COMM_ITER *realm_iter=NULL;
1431   TR_REALM *realm=NULL;
1432   TRP_UPD *upd=NULL;
1433   TRP_RC rc=TRP_ERROR;
1434   
1435   comm_iter=tr_comm_iter_new(tmp_ctx);
1436   realm_iter=tr_comm_iter_new(tmp_ctx);
1437   if ((comm_iter==NULL) || (realm_iter==NULL)) {
1438     tr_err("trps_select_comm_updates_for_peer: unable to allocate iterator.");
1439     rc=TRP_NOMEM;
1440     goto cleanup;
1441   }
1442
1443   /* do every community */
1444   for (comm=tr_comm_table_iter_first(comm_iter, trps->ctable);
1445        comm!=NULL;
1446        comm=tr_comm_table_iter_next(comm_iter)) {
1447     /* do every realm in this community */
1448     tr_debug("trps_select_comm_updates_for_peer: looking through community %.*s",
1449              tr_comm_get_id(comm)->len,
1450              tr_comm_get_id(comm)->buf);
1451     for (realm=tr_realm_iter_first(realm_iter, trps->ctable, tr_comm_get_id(comm));
1452          realm!=NULL;
1453          realm=tr_realm_iter_next(realm_iter)) {
1454       /* get the update for this comm/realm */
1455       tr_debug("trps_select_comm_updates_for_peer: adding realm %.*s",
1456                tr_realm_get_id(realm)->len,
1457                tr_realm_get_id(realm)->buf);
1458       upd=trps_comm_update(mem_ctx, trps, peer_gssname, comm, realm);
1459       if (upd!=NULL)
1460         g_ptr_array_add(updates, upd);
1461     }
1462   }
1463
1464 cleanup:
1465   talloc_free(tmp_ctx);
1466   return rc;
1467 }
1468
1469
1470 /* helper for trps_update_one_peer. Frees the TRP_UPD pointed to by a GPtrArray element */
1471 static void trps_trp_upd_destroy(gpointer data)
1472 {
1473   trp_upd_free((TRP_UPD *)data);
1474 }
1475
1476 /* all routes/communities to a single peer, unless comm/realm are specified (both or neither must be NULL) */
1477 static TRP_RC trps_update_one_peer(TRPS_INSTANCE *trps,
1478                                    TRP_PEER *peer,
1479                                    TRP_UPDATE_TYPE update_type,
1480                                    TR_NAME *comm,
1481                                    TR_NAME *realm)
1482 {
1483   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1484   TR_MSG msg; /* not a pointer! */
1485   TRP_UPD *upd=NULL;
1486   TRP_ROUTE *route=NULL;
1487   size_t ii=0;
1488   char *encoded=NULL;
1489   TRP_RC rc=TRP_ERROR;
1490   TR_NAME *peer_label=trp_peer_get_label(peer);
1491   GPtrArray *updates=g_ptr_array_new_with_free_func(trps_trp_upd_destroy);
1492
1493   if (updates==NULL) {
1494     tr_err("trps_update_one_peer: unable to allocate updates array.");
1495     rc=TRP_NOMEM;
1496     goto cleanup;
1497   }
1498
1499   switch (update_type) {
1500   case TRP_UPDATE_TRIGGERED:
1501     tr_debug("trps_update_one_peer: preparing triggered update for %.*s",
1502              peer_label->len, peer_label->buf);
1503     break;
1504   case TRP_UPDATE_SCHEDULED:
1505     tr_debug("trps_update_one_peer: preparing scheduled update for %.*s",
1506              peer_label->len, peer_label->buf);
1507     break;
1508   case TRP_UPDATE_REQUESTED:
1509     tr_debug("trps_update_one_peer: preparing requested update for %.*s",
1510              peer_label->len, peer_label->buf);
1511     break;
1512   default:
1513     tr_err("trps_update_one_peer: invalid update type requested.");
1514     rc=TRP_BADARG;
1515     goto cleanup;
1516   }
1517
1518   /* First, gather route updates. */
1519   tr_debug("trps_update_one_peer: selecting route updates for %.*s.", peer_label->len, peer_label->buf);
1520   if ((comm==NULL) && (realm==NULL)) {
1521     /* do all realms */
1522     rc=trps_select_route_updates_for_peer(tmp_ctx,
1523                                           updates,
1524                                           trps,
1525                                           peer_label,
1526                                           update_type==TRP_UPDATE_TRIGGERED);
1527   } else if ((comm!=NULL) && (realm!=NULL)) {
1528     /* a single community/realm was requested */
1529     route=trps_select_realm_update(trps, comm, realm, peer_label);
1530     if (route==NULL) {
1531       /* we have no actual update to send back, MUST send a retraction */
1532       tr_debug("trps_update_one_peer: community/realm without route requested, sending mandatory retraction.");
1533       route=trp_route_new(tmp_ctx);
1534       trp_route_set_comm(route, tr_dup_name(comm));
1535       trp_route_set_realm(route, tr_dup_name(realm));
1536       trp_route_set_peer(route, tr_new_name(""));
1537       trp_route_set_metric(route, TRP_METRIC_INFINITY);
1538       trp_route_set_trust_router(route, tr_new_name(""));
1539       trp_route_set_next_hop(route, tr_new_name(""));
1540     }
1541     upd=trps_route_to_upd(tmp_ctx, trps, route);
1542     if (upd==NULL) {
1543       tr_err("trps_update_one_peer: unable to allocate route update.");
1544       rc=TRP_NOMEM;
1545       goto cleanup;
1546     }
1547     g_ptr_array_add(updates, upd);
1548   } else {
1549     tr_err("trps_update_one_peer: error: only comm or realm was specified. Need both or neither.");
1550     rc=TRP_ERROR;
1551     goto cleanup;
1552   }
1553
1554   /* Second, gather community updates */
1555   tr_debug("trps_update_one_peer: selecting community updates for %.*s.", peer_label->len, peer_label->buf);
1556   rc=trps_select_comm_updates_for_peer(tmp_ctx, updates, trps, peer_label);
1557
1558   /* see if we have anything to send */
1559   if (updates->len<=0)
1560     tr_debug("trps_update_one_peer: no updates for %.*s", peer_label->len, peer_label->buf);
1561   else {
1562     tr_debug("trps_update_one_peer: sending %d update messages.", updates->len);
1563     for (ii=0; ii<updates->len; ii++) {
1564       upd=(TRP_UPD *)g_ptr_array_index(updates, ii);
1565       /* now encode the update message */
1566       tr_msg_set_trp_upd(&msg, upd);
1567       encoded=tr_msg_encode(&msg);
1568       if (encoded==NULL) {
1569         tr_err("trps_update_one_peer: error encoding update.");
1570         rc=TRP_ERROR;
1571         goto cleanup;
1572       }
1573
1574       tr_debug("trps_update_one_peer: adding message to queue.");
1575       if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS)
1576         tr_err("trps_update_one_peer: error queueing update.");
1577       else
1578         tr_debug("trps_update_one_peer: update queued successfully.");
1579
1580       tr_msg_free_encoded(encoded);
1581       encoded=NULL;
1582     }
1583   }
1584
1585   rc=TRP_SUCCESS;
1586
1587 cleanup:
1588   if (updates!=NULL)
1589     g_ptr_array_free(updates, TRUE); /* frees any TRP_UPD records */
1590   talloc_free(tmp_ctx);
1591   return rc;
1592 }
1593
1594 /* all routes/communities to all peers */
1595 TRP_RC trps_update(TRPS_INSTANCE *trps, TRP_UPDATE_TYPE update_type)
1596 {
1597   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1598   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
1599   TRP_PEER *peer=NULL;
1600   TRP_RC rc=TRP_SUCCESS;
1601
1602   if (trps->ptable==NULL)
1603     return TRP_SUCCESS; /* no peers, nothing to do */
1604
1605   if (iter==NULL) {
1606     tr_err("trps_update: failed to allocate peer table iterator.");
1607     talloc_free(tmp_ctx);
1608     return TRP_NOMEM;
1609   }
1610
1611   for (peer=trp_ptable_iter_first(iter, trps->ptable);
1612        peer!=NULL && rc==TRP_SUCCESS;
1613        peer=trp_ptable_iter_next(iter))
1614   {
1615     if (!trps_peer_connected(trps, peer)) {
1616       TR_NAME *peer_label=trp_peer_get_label(peer);
1617       tr_debug("trps_update: no TRP connection to %.*s, skipping.",
1618                peer_label->len, peer_label->buf);
1619       continue;
1620     }
1621     rc=trps_update_one_peer(trps, peer, update_type, NULL, NULL);
1622   }
1623
1624   tr_debug("trps_update: rc=%u after attempting update.", rc);
1625   trp_ptable_iter_free(iter);
1626   trp_rtable_clear_triggered(trps->rtable); /* don't re-send triggered updates */
1627   talloc_free(tmp_ctx);
1628   return rc;
1629 }        
1630
1631 TRP_RC trps_add_route(TRPS_INSTANCE *trps, TRP_ROUTE *route)
1632 {
1633   trp_rtable_add(trps->rtable, route); /* should return status */
1634   return TRP_SUCCESS; 
1635 }
1636
1637 /* steals the peer object */
1638 TRP_RC trps_add_peer(TRPS_INSTANCE *trps, TRP_PEER *peer)
1639 {
1640   if (trps->ptable==NULL) {
1641     trps->ptable=trp_ptable_new(trps);
1642     if (trps->ptable==NULL)
1643       return TRP_NOMEM;
1644   }
1645   return trp_ptable_add(trps->ptable, peer);
1646 }
1647
1648 TRP_PEER *trps_get_peer_by_gssname(TRPS_INSTANCE *trps, TR_NAME *gssname)
1649 {
1650   if (trps->ptable==NULL)
1651     return NULL;
1652
1653   return trp_ptable_find_gss_name(trps->ptable, gssname);
1654 }
1655
1656 TRP_PEER *trps_get_peer_by_servicename(TRPS_INSTANCE *trps, TR_NAME *servicename)
1657 {
1658   if (trps->ptable==NULL)
1659     return NULL;
1660
1661   return trp_ptable_find_servicename(trps->ptable, servicename);
1662 }
1663
1664 int trps_peer_connected(TRPS_INSTANCE *trps, TRP_PEER *peer)
1665 {
1666   TRPC_INSTANCE *trpc=trps_find_trpc(trps, peer);
1667   if (trpc==NULL)
1668     return 0;
1669
1670   if (trpc_get_status(trpc)==TRP_CONNECTION_UP)
1671     return 1;
1672   else
1673     return 0;
1674 }
1675
1676
1677 static TRP_RC trps_handle_request(TRPS_INSTANCE *trps, TRP_REQ *req)
1678 {
1679   TR_NAME *comm=NULL;
1680   TR_NAME *realm=NULL;
1681
1682   tr_debug("trps_handle_request: handling TRP request.");
1683
1684   if (trps_validate_request(trps, req) != TRP_SUCCESS) {
1685     tr_notice("trps_handle_request: received invalid TRP request.");
1686     return TRP_ERROR;
1687   }
1688
1689   if (!trp_req_is_wildcard(req)) {
1690     comm=trp_req_get_comm(req);
1691     realm=trp_req_get_realm(req);
1692     tr_debug("trps_handle_request: route for %.*s/%.*s requested.",
1693              comm->len, comm->buf, realm->len, realm->buf);
1694   } else {
1695     tr_debug("trps_handle_request: all routes requested.");
1696     /* leave comm/realm NULL */
1697   }
1698   return trps_update_one_peer(trps,
1699                               trps_get_peer_by_gssname(trps, trp_req_get_peer(req)),
1700                               TRP_UPDATE_REQUESTED,
1701                               comm,
1702                               realm);
1703 }
1704
1705
1706 TRP_RC trps_handle_tr_msg(TRPS_INSTANCE *trps, TR_MSG *tr_msg)
1707 {
1708   TRP_RC rc=TRP_ERROR;
1709
1710   switch (tr_msg_get_msg_type(tr_msg)) {
1711   case TRP_UPDATE:
1712     rc=trps_handle_update(trps, tr_msg_get_trp_upd(tr_msg));
1713     if (rc==TRP_SUCCESS) {
1714       rc=trps_update_active_routes(trps);
1715       trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
1716     }
1717     return rc;
1718
1719   case TRP_REQUEST:
1720     rc=trps_handle_request(trps, tr_msg_get_trp_req(tr_msg));
1721     return rc;
1722
1723   default:
1724     /* unknown error or one we don't care about (e.g., TID messages) */
1725     return TRP_ERROR;
1726   }
1727 }
1728
1729 /* send wildcard route request to a peer */
1730 TRP_RC trps_wildcard_route_req(TRPS_INSTANCE *trps, TR_NAME *peer_servicename)
1731 {
1732   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1733   TRP_PEER *peer=trps_get_peer_by_servicename(trps, peer_servicename);
1734   TR_MSG msg; /* not a pointer */
1735   TRP_REQ *req=trp_req_new(tmp_ctx);
1736   char *encoded=NULL;
1737   TRP_RC rc=TRP_ERROR;
1738
1739   if (peer==NULL) {
1740     tr_err("trps_wildcard_route_req: unknown peer (%.*s).", peer_servicename->len, peer_servicename->buf);
1741     rc=TRP_BADARG;
1742     goto cleanup;
1743   }
1744   if ((req==NULL) || (trp_req_make_wildcard(req)!=TRP_SUCCESS)) {
1745     tr_err("trps_wildcard_route_req: unable to create wildcard TRP request.");
1746     rc=TRP_NOMEM;
1747     goto cleanup;
1748   }
1749
1750   tr_msg_set_trp_req(&msg, req);
1751   encoded=tr_msg_encode(&msg);
1752   if (encoded==NULL) {
1753     tr_err("trps_wildcard_route_req: error encoding wildcard TRP request.");
1754     rc=TRP_ERROR;
1755     goto cleanup;
1756   }
1757
1758   tr_debug("trps_wildcard_route_req: adding message to queue.");
1759   if (trps_send_msg(trps, peer, encoded) != TRP_SUCCESS) {
1760     tr_err("trps_wildcard_route_req: error queueing request.");
1761     rc=TRP_ERROR;
1762   } else {
1763     tr_debug("trps_wildcard_route_req: request queued successfully.");
1764     rc=TRP_SUCCESS;
1765   }
1766
1767 cleanup:
1768   if (encoded!=NULL)
1769     tr_msg_free_encoded(encoded);
1770   if (req!=NULL)
1771     trp_req_free(req);
1772
1773   talloc_free(tmp_ctx);
1774   return rc;
1775 }