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