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