Open all ports for servers. Disallow IPv4-mapped IPv6 addrs.
[trust_router.git] / tr / tr_trp.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 <stdio.h>
36 #include <pthread.h>
37 #include <fcntl.h>
38 #include <event2/event.h>
39 #include <talloc.h>
40 #include <errno.h>
41 #include <unistd.h>
42 #include <string.h>
43 #include <sys/time.h>
44 #include <time.h>
45
46 #include <gsscon.h>
47 #include <tr.h>
48 #include <tr_mq.h>
49 #include <tr_rp.h>
50 #include <trp_internal.h>
51 #include <trp_ptable.h>
52 #include <trp_rtable.h>
53 #include <tr_config.h>
54 #include <tr_event.h>
55 #include <tr_msg.h>
56 #include <tr_trp.h>
57 #include <tr_debug.h>
58
59 /* data for event callbacks */
60 struct tr_trps_event_cookie {
61   TRPS_INSTANCE *trps;
62   TR_CFG_MGR *cfg_mgr;
63   struct event *ev;
64 };
65
66 /* callback to schedule event to process messages */
67 static void tr_trps_mq_cb(TR_MQ *mq, void *arg)
68 {
69   struct event *mq_ev=(struct event *)arg;
70   event_active(mq_ev, 0, 0);
71 }
72
73 static void msg_free_helper(void *p)
74 {
75   tr_msg_free_decoded((TR_MSG *)p);
76 }
77
78 static void tr_free_name_helper(void *arg)
79 {
80   tr_free_name((TR_NAME *)arg);
81 }
82
83 /* takes a TR_MSG and puts it in a TR_MQ_MSG for processing by the main thread */
84 static TRP_RC tr_trps_msg_handler(TRPS_INSTANCE *trps,
85                                   TRP_CONNECTION *conn,
86                                   TR_MSG *tr_msg)
87 {
88   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
89   TR_MQ_MSG *mq_msg=NULL;
90
91   /* n.b., conn is available here, but do not hold onto the reference
92    * because it may be cleaned up if the originating connection goes
93    * down before the message is processed */
94   mq_msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_MSG_RECEIVED, TR_MQ_PRIO_NORMAL);
95   if (mq_msg==NULL) {
96     return TRP_NOMEM;
97   }
98   tr_mq_msg_set_payload(mq_msg, (void *)tr_msg, msg_free_helper);
99   trps_mq_add(trps, mq_msg);
100   talloc_free(tmp_ctx); /* cleans up the message if it did not get appended correctly */
101   return TRP_SUCCESS;
102 }
103
104
105 static int tr_trps_gss_handler(gss_name_t client_name, gss_buffer_t gss_name,
106                                void *cookie_in)
107 {
108   struct tr_trps_event_cookie *cookie=(struct tr_trps_event_cookie *)cookie_in;
109   TRPS_INSTANCE *trps = cookie->trps;
110   TR_CFG_MGR *cfg_mgr = cookie->cfg_mgr;
111   TR_NAME name={gss_name->value, gss_name->length};
112
113   tr_debug("tr_trps_gss_handler()");
114
115   if ((!client_name) || (!gss_name) || (!trps) || (!cfg_mgr)) {
116     tr_debug("tr_trps_gss_handler: Bad parameters.");
117     return -1;
118   }
119   
120   /* look up the TRPS peer matching the GSS name */
121   if (NULL==trps_get_peer_by_gssname(trps, &name)) {
122     tr_warning("tr_trps_gss_handler: Connection attempt from unknown peer (GSS name: %.*s).", name.len, name.buf);
123     return -1;
124   }
125
126   tr_debug("Client's GSS Name: %.*s", name.len, name.buf);
127   return 0;
128 }
129
130 /* data passed to thread */
131 struct trps_thread_data {
132   TRP_CONNECTION *conn;
133   TRPS_INSTANCE *trps;
134 };
135 /* thread to handle GSS connections from peers */
136 static void *tr_trps_thread(void *arg)
137 {
138   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
139   struct trps_thread_data *thread_data=talloc_get_type_abort(arg, struct trps_thread_data);
140   TRP_CONNECTION *conn=thread_data->conn;
141   TRPS_INSTANCE *trps=thread_data->trps;
142   TR_MQ_MSG *msg=NULL;
143
144   tr_debug("tr_trps_thread: started");
145   if (trps_authorize_connection(trps, conn)!=TRP_SUCCESS)
146     goto cleanup;
147
148   msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPS_CONNECTED, TR_MQ_PRIO_HIGH);
149   tr_mq_msg_set_payload(msg, (void *)tr_dup_name(trp_connection_get_peer(conn)), tr_free_name_helper);
150   if (msg==NULL) {
151     tr_err("tr_trps_thread: error allocating TR_MQ_MSG");
152     goto cleanup;
153   } 
154   trps_mq_add(trps, msg); /* steals msg context */
155   msg=NULL;
156
157   trps_handle_connection(trps, conn);
158
159 cleanup:
160   msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPS_DISCONNECTED, TR_MQ_PRIO_HIGH);
161   tr_mq_msg_set_payload(msg, (void *)conn, NULL); /* do not pass a free routine */
162   if (msg==NULL)
163     tr_err("tr_trps_thread: error allocating TR_MQ_MSG");
164   else
165     trps_mq_add(trps, msg);
166   tr_debug("tr_trps_thread: exit");
167   talloc_free(tmp_ctx);
168   return NULL;
169 }
170
171 /* called when a connection to the TRPS port is received */
172 static void tr_trps_event_cb(int listener, short event, void *arg)
173 {
174   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
175   TRPS_INSTANCE *trps = talloc_get_type_abort(arg, TRPS_INSTANCE); /* aborts on wrong type */
176   TRP_CONNECTION *conn=NULL;
177   TR_NAME *gssname=NULL;
178   char *name=NULL;
179   struct trps_thread_data *thread_data=NULL;
180
181   if (0==(event & EV_READ)) {
182     tr_debug("tr_trps_event_cb: unexpected event on TRPS socket (event=0x%X)", event);
183   } else {
184     /* create a thread to handle this connection */
185     if (asprintf(&name, "trustrouter@%s", trps->hostname)==-1) {
186       goto cleanup;
187     }
188     gssname=tr_new_name(name);
189     free(name); name=NULL;
190     conn=trp_connection_accept(tmp_ctx, listener, gssname);
191     if (conn!=NULL) {
192       /* need to monitor this fd and trigger events when read becomes possible */
193       thread_data=talloc(conn, struct trps_thread_data);
194       if (thread_data==NULL) {
195         tr_err("tr_trps_event_cb: unable to allocate trps_thread_data");
196         talloc_free(tmp_ctx);
197         return;
198       }
199       thread_data->conn=conn;
200       thread_data->trps=trps;
201       trps_add_connection(trps, conn); /* remember the connection */
202       pthread_create(trp_connection_get_thread(conn), NULL, tr_trps_thread, thread_data);
203     }
204   }
205
206  cleanup:
207   talloc_free(tmp_ctx);
208 }
209
210 static void tr_trps_cleanup_conn(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
211 {
212   /* everything belonging to the thread is in the TRP_CONNECTION
213    * associated with it */
214   tr_debug("tr_trps_cleanup_conn: freeing %p", conn);
215   pthread_join(*trp_connection_get_thread(conn), NULL);
216   trps_remove_connection(trps, conn);
217   trp_connection_free(conn);
218   tr_debug("tr_trps_cleanup_conn: deleted connection");
219 }
220
221 static void tr_trps_cleanup_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *trpc)
222 {
223   pthread_join(*trp_connection_get_thread(trpc_get_conn(trpc)), NULL);
224   trps_remove_trpc(trps, trpc);
225   trpc_free(trpc);
226   tr_debug("tr_trps_cleanup_trpc: deleted connection");
227 }
228
229 static void tr_trps_print_route_table(TRPS_INSTANCE *trps, FILE *f)
230 {
231   char *table=trp_rtable_to_str(NULL, trps->rtable, " | ", NULL);
232   if (table==NULL)
233     fprintf(f, "Unable to print route table.\n");
234   else {
235     fprintf(f, "%s\n", table);
236     talloc_free(table);
237   }
238 }
239
240 static void tr_trps_process_mq(int socket, short event, void *arg)
241 {
242   TRPS_INSTANCE *trps=talloc_get_type_abort(arg, TRPS_INSTANCE);
243   TR_MQ_MSG *msg=NULL;
244   const char *s=NULL;
245
246   msg=trps_mq_pop(trps);
247   while (msg!=NULL) {
248     s=tr_mq_msg_get_message(msg);
249     if (0==strcmp(s, TR_MQMSG_TRPS_CONNECTED)) {
250       TR_NAME *gssname=(TR_NAME *)tr_mq_msg_get_payload(msg);
251       TRP_PEER *peer=trps_get_peer_by_gssname(trps, gssname);
252       if (peer==NULL)
253         tr_err("tr_trps_process_mq: incoming connection from unknown peer (%s) reported.", gssname->buf);
254       else {
255         trp_peer_set_incoming_status(peer, PEER_CONNECTED);
256         tr_err("tr_trps_process_mq: incoming connection from %s established.", gssname->buf);
257       }
258     }
259     else if (0==strcmp(s, TR_MQMSG_TRPS_DISCONNECTED)) {
260       TRP_CONNECTION *conn=talloc_get_type_abort(tr_mq_msg_get_payload(msg), TRP_CONNECTION);
261       TR_NAME *gssname=trp_connection_get_gssname(conn);
262       TRP_PEER *peer=trps_get_peer_by_gssname(trps, gssname);
263       if (peer==NULL) {
264         tr_err("tr_trps_process_mq: incoming connection from unknown peer (%s) lost.",
265                trp_connection_get_gssname(conn)->buf);
266       } else {
267         trp_peer_set_incoming_status(peer, PEER_DISCONNECTED);
268         tr_trps_cleanup_conn(trps, conn);
269         tr_err("tr_trps_process_mq: incoming connection from %s lost.", gssname->buf);
270       }
271     }
272     else if (0==strcmp(s, TR_MQMSG_TRPC_CONNECTED)) {
273       TR_NAME *svcname=(TR_NAME *)tr_mq_msg_get_payload(msg);
274       TRP_PEER *peer=trps_get_peer_by_servicename(trps, svcname);
275       if (peer==NULL)
276         tr_err("tr_trps_process_mq: outgoing connection to unknown peer (%s) reported.", svcname->buf);
277       else {
278         trp_peer_set_outgoing_status(peer, PEER_CONNECTED);
279         tr_err("tr_trps_process_mq: outgoing connection to %s established.", svcname->buf);
280       }
281     }
282     else if (0==strcmp(s, TR_MQMSG_TRPC_DISCONNECTED)) {
283       /* trpc connection died */
284       TRPC_INSTANCE *trpc=talloc_get_type_abort(tr_mq_msg_get_payload(msg), TRPC_INSTANCE);
285       TR_NAME *gssname=trpc_get_gssname(trpc);
286       TRP_PEER *peer=trps_get_peer_by_servicename(trps, gssname);
287       if (peer==NULL)
288         tr_err("tr_trps_process_mq: outgoing connection to unknown peer (%s) lost.", gssname->buf);
289       else {
290         trp_peer_set_outgoing_status(peer, PEER_DISCONNECTED);
291         tr_err("tr_trps_process_mq: outgoing connection to %s lost.", gssname->buf);
292         tr_trps_cleanup_trpc(trps, trpc);
293       }
294     }
295
296     else if (0==strcmp(s, TR_MQMSG_MSG_RECEIVED)) {
297       if (trps_handle_tr_msg(trps, tr_mq_msg_get_payload(msg))!=TRP_SUCCESS)
298         tr_notice("tr_trps_process_mq: error handling message.");
299       else {
300         tr_trps_print_route_table(trps, stderr);
301       }
302     }
303     else
304       tr_notice("tr_trps_process_mq: unknown message '%s' received.", tr_mq_msg_get_message(msg));
305
306     tr_mq_msg_free(msg);
307     msg=trps_mq_pop(trps);
308   }
309 }
310
311 static void tr_trps_update(int listener, short event, void *arg)
312 {
313   struct tr_trps_event_cookie *cookie=talloc_get_type_abort(arg, struct tr_trps_event_cookie);
314   TRPS_INSTANCE *trps=cookie->trps;
315   struct event *ev=cookie->ev;
316
317   tr_debug("tr_trps_update: sending scheduled route/community updates.");
318   trps_update(trps, TRP_UPDATE_SCHEDULED);
319   event_add(ev, &(trps->update_interval));
320   tr_debug("tr_trps_update: update interval=%d", trps->update_interval.tv_sec);
321 }
322
323 static void tr_trps_sweep(int listener, short event, void *arg)
324 {
325   struct tr_trps_event_cookie *cookie=talloc_get_type_abort(arg, struct tr_trps_event_cookie);
326   TRPS_INSTANCE *trps=cookie->trps;
327   struct event *ev=cookie->ev;
328
329   tr_debug("tr_trps_sweep: sweeping routes.");
330   trps_sweep_routes(trps);
331   tr_debug("tr_trps_sweep: sweeping communities.");
332   trps_sweep_ctable(trps);
333   tr_trps_print_route_table(trps, stderr);
334   /* schedule the event to run again */
335   event_add(ev, &(trps->sweep_interval));
336 }
337
338 static void tr_connection_update(int listener, short event, void *arg)
339 {
340   struct tr_trps_event_cookie *cookie=talloc_get_type_abort(arg, struct tr_trps_event_cookie);
341   TRPS_INSTANCE *trps=cookie->trps;
342   struct event *ev=cookie->ev;
343
344   tr_debug("tr_connection_update: checking peer connections.");
345   tr_connect_to_peers(trps, ev);
346   /* schedule the event to run again */
347   event_add(ev, &(trps->connect_interval));
348 }
349
350 static int tr_trps_events_destructor(void *obj)
351 {
352   TR_TRPS_EVENTS *ev=talloc_get_type_abort(obj, TR_TRPS_EVENTS);
353   if (ev->mq_ev!=NULL)
354     event_free(ev->mq_ev);
355   if (ev->connect_ev!=NULL)
356     event_free(ev->connect_ev);
357   if (ev->update_ev!=NULL)
358     event_free(ev->update_ev);
359   if (ev->sweep_ev!=NULL)
360     event_free(ev->sweep_ev);
361   return 0;
362 }
363 static TR_TRPS_EVENTS *tr_trps_events_new(TALLOC_CTX *mem_ctx)
364 {
365   TR_TRPS_EVENTS *ev=talloc(mem_ctx, TR_TRPS_EVENTS);
366   if (ev!=NULL) {
367     ev->listen_ev=talloc(ev, struct tr_socket_event);
368     ev->mq_ev=NULL;
369     ev->connect_ev=NULL;
370     ev->update_ev=NULL;
371     ev->sweep_ev=NULL;
372     if (ev->listen_ev==NULL) {
373       talloc_free(ev);
374       ev=NULL;
375     } else {
376       talloc_set_destructor((void *)ev, tr_trps_events_destructor);
377     }
378   }
379   return ev;
380 }
381
382 static void tr_trps_events_free(TR_TRPS_EVENTS *ev)
383 {
384   talloc_free(ev);
385 }
386
387 /* Configure the trps instance and set up its event handler.
388  * Fills in trps_ev, which should be allocated by caller. */
389 TRP_RC tr_trps_event_init(struct event_base *base, TR_INSTANCE *tr)
390 {
391   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
392   struct tr_socket_event *listen_ev=NULL;
393   struct tr_trps_event_cookie *trps_cookie=NULL;
394   struct tr_trps_event_cookie *connection_cookie=NULL;
395   struct tr_trps_event_cookie *update_cookie=NULL;
396   struct tr_trps_event_cookie *sweep_cookie=NULL;
397   struct timeval zero_time={0,0};
398   TRP_RC retval=TRP_ERROR;
399   size_t ii=0;
400
401   if (tr->events != NULL) {
402     tr_notice("tr_trps_event_init: tr->events was not null. Freeing before reallocating..");
403     tr_trps_events_free(tr->events);
404   }
405
406   tr->events=tr_trps_events_new(tmp_ctx);
407   if (tr->events == NULL) {
408     tr_debug("tr_trps_event_init: unable to allocate event handles.");
409     retval=TRP_NOMEM;
410     goto cleanup;
411   }
412
413   /* get convenient handles */
414   listen_ev=tr->events->listen_ev;
415
416   /* Create the cookie for callbacks. It will end up part of the trps context, so it will
417    * be cleaned up when trps is freed by talloc_free. */
418   trps_cookie=talloc(tr->events, struct tr_trps_event_cookie);
419   if (trps_cookie == NULL) {
420     tr_debug("tr_trps_event_init: Unable to allocate trps_cookie.");
421     retval=TRP_NOMEM;
422     tr_trps_events_free(tr->events);
423     tr->events=NULL;
424     goto cleanup;
425   }
426   trps_cookie->trps=tr->trps;
427   trps_cookie->cfg_mgr=tr->cfg_mgr;
428
429   /* get a trps listener */
430   listen_ev->n_sock_fd=trps_get_listener(tr->trps,
431                                          tr_trps_msg_handler,
432                                          tr_trps_gss_handler,
433                                          tr->cfg_mgr->active->internal->hostname,
434                                          tr->cfg_mgr->active->internal->trps_port,
435                                          (void *)trps_cookie,
436                                          listen_ev->sock_fd,
437                                          TR_MAX_SOCKETS);
438   if (listen_ev->n_sock_fd==0) {
439     tr_crit("Error opening TRP server socket.");
440     retval=TRP_ERROR;
441     tr_trps_events_free(tr->events);
442     tr->events=NULL;
443     goto cleanup;
444   }
445
446   /* Set up events for the sockets */
447   for (ii=0; ii<listen_ev->n_sock_fd; ii++) {
448     listen_ev->ev[ii]=event_new(base,
449                                 listen_ev->sock_fd[ii],
450                                 EV_READ|EV_PERSIST,
451                                 tr_trps_event_cb,
452                                 (void *)(tr->trps));
453     event_add(listen_ev->ev[ii], NULL);
454   }
455   
456   /* now set up message queue processing event, only triggered by
457    * tr_trps_mq_cb() */
458   tr->events->mq_ev=event_new(base,
459                               0,
460                               EV_PERSIST,
461                               tr_trps_process_mq,
462                               (void *)(tr->trps));
463   tr_mq_set_notify_cb(tr->trps->mq, tr_trps_mq_cb, tr->events->mq_ev);
464
465   /* now set up the peer connection timer event */
466   connection_cookie=talloc(tr->events, struct tr_trps_event_cookie);
467   if (connection_cookie == NULL) {
468     tr_debug("tr_trps_event_init: Unable to allocate connection_cookie.");
469     retval=TRP_NOMEM;
470     tr_trps_events_free(tr->events);
471     tr->events=NULL;
472     goto cleanup;
473   }
474   connection_cookie->trps=tr->trps;
475   connection_cookie->cfg_mgr=tr->cfg_mgr;
476   tr->events->connect_ev=event_new(base, -1, EV_TIMEOUT, tr_connection_update, (void *)connection_cookie);
477   connection_cookie->ev=tr->events->connect_ev; /* in case it needs to frob the event */
478   /* The first time, do this immediately. Thereafter, it will retrigger every trps->connect_interval */
479   event_add(tr->events->connect_ev, &zero_time);
480
481   /* now set up the route update timer event */
482   update_cookie=talloc(tr->events, struct tr_trps_event_cookie);
483   if (update_cookie == NULL) {
484     tr_debug("tr_trps_event_init: Unable to allocate update_cookie.");
485     retval=TRP_NOMEM;
486     tr_trps_events_free(tr->events);
487     tr->events=NULL;
488     goto cleanup;
489   }
490   update_cookie->trps=tr->trps;
491   update_cookie->cfg_mgr=tr->cfg_mgr;
492   tr->events->update_ev=event_new(base, -1, EV_TIMEOUT, tr_trps_update, (void *)update_cookie);
493   update_cookie->ev=tr->events->update_ev; /* in case it needs to frob the event */
494   event_add(tr->events->update_ev, &(tr->trps->update_interval));
495
496   /* now set up the route table sweep timer event */
497   sweep_cookie=talloc(tr->events, struct tr_trps_event_cookie);
498   if (sweep_cookie == NULL) {
499     tr_debug("tr_trps_event_init: Unable to allocate sweep_cookie.");
500     retval=TRP_NOMEM;
501     tr_trps_events_free(tr->events);
502     tr->events=NULL;
503     goto cleanup;
504   }
505   sweep_cookie->trps=tr->trps;
506   sweep_cookie->cfg_mgr=tr->cfg_mgr;
507   tr->events->sweep_ev=event_new(base, -1, EV_TIMEOUT, tr_trps_sweep, (void *)sweep_cookie);
508   sweep_cookie->ev=tr->events->sweep_ev; /* in case it needs to frob the event */
509   event_add(tr->events->sweep_ev, &(tr->trps->sweep_interval));
510
511   talloc_steal(tr, tr->events);
512   retval=TRP_SUCCESS;
513
514 cleanup:
515   talloc_free(tmp_ctx);
516   return retval;
517 }
518
519
520 struct trpc_notify_cb_data {
521   int msg_ready;
522   pthread_cond_t cond;
523   pthread_mutex_t mutex;
524 };
525
526 static void tr_trpc_mq_cb(TR_MQ *mq, void *arg)
527 {
528   struct trpc_notify_cb_data *cb_data=(struct trpc_notify_cb_data *) arg;
529   pthread_mutex_lock(&(cb_data->mutex));
530   if (!cb_data->msg_ready) {
531     cb_data->msg_ready=1;
532     pthread_cond_signal(&(cb_data->cond));
533   }
534   pthread_mutex_unlock(&(cb_data->mutex));
535 }
536
537 /* data passed to thread */
538 struct trpc_thread_data {
539   TRPC_INSTANCE *trpc;
540   TRPS_INSTANCE *trps;
541 };
542 static void *tr_trpc_thread(void *arg)
543 {
544   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
545   struct trpc_thread_data *thread_data=talloc_get_type_abort(arg, struct trpc_thread_data);
546   TRPC_INSTANCE *trpc=thread_data->trpc;
547   TRPS_INSTANCE *trps=thread_data->trps;
548   TRP_RC rc=TRP_ERROR;
549   TR_MQ_MSG *msg=NULL;
550   const char *msg_type=NULL;
551   char *encoded_msg=NULL;
552   TR_NAME *peer_gssname=NULL;
553   int n_sent=0;
554   int exit_loop=0;
555
556   struct trpc_notify_cb_data cb_data={0,
557                                       PTHREAD_COND_INITIALIZER,
558                                       PTHREAD_MUTEX_INITIALIZER};
559
560   tr_debug("tr_trpc_thread: started");
561
562   /* set up the mq for receiving */
563   pthread_mutex_lock(&(cb_data.mutex)); /* hold this lock until we enter the main loop */
564
565   tr_mq_lock(trpc->mq);
566   tr_mq_set_notify_cb(trpc->mq, tr_trpc_mq_cb, (void *) &cb_data);
567   tr_mq_unlock(trpc->mq);
568
569   rc=trpc_connect(trpc);
570   if (rc!=TRP_SUCCESS) {
571     tr_notice("tr_trpc_thread: failed to initiate connection to %s:%d.",
572               trpc_get_server(trpc),
573               trpc_get_port(trpc));
574   } else {
575     peer_gssname=trp_connection_get_peer(trpc_get_conn(trpc));
576     if (peer_gssname==NULL) {
577       tr_err("tr_trpc_thread: could not duplicate peer_gssname.");
578       talloc_free(tmp_ctx);
579       return NULL;
580     }
581     tr_debug("tr_trpc_thread: connected to peer %s", peer_gssname->buf);
582
583     msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_CONNECTED, TR_MQ_PRIO_HIGH);
584     tr_mq_msg_set_payload(msg, (void *)tr_dup_name(peer_gssname), tr_free_name_helper);
585     if (msg==NULL) {
586       tr_err("tr_trpc_thread: error allocating TR_MQ_MSG");
587       talloc_free(tmp_ctx);
588       return NULL;
589     }
590     trps_mq_add(trps, msg); /* steals msg context */
591     msg=NULL;
592
593     while(!exit_loop) {
594       cb_data.msg_ready=0;
595       pthread_cond_wait(&(cb_data.cond), &(cb_data.mutex));
596       /* verify the condition */
597       if (cb_data.msg_ready) {
598         for (msg=trpc_mq_pop(trpc),n_sent=0; msg!=NULL; msg=trpc_mq_pop(trpc),n_sent++) {
599           msg_type=tr_mq_msg_get_message(msg);
600
601           if (0==strcmp(msg_type, TR_MQMSG_ABORT)) {
602             exit_loop=1;
603             break;
604           }
605           else if (0==strcmp(msg_type, TR_MQMSG_TRPC_SEND)) {
606             encoded_msg=tr_mq_msg_get_payload(msg);
607             if (encoded_msg==NULL)
608               tr_notice("tr_trpc_thread: null outgoing TRP message.");
609             else {
610               rc = trpc_send_msg(trpc, encoded_msg);
611               if (rc!=TRP_SUCCESS) {
612                 tr_notice("tr_trpc_thread: trpc_send_msg failed.");
613                 exit_loop=1;
614                 break;
615               }
616             }
617           }
618           else
619             tr_notice("tr_trpc_thread: unknown message '%s' received.", msg_type);
620
621           tr_mq_msg_free(msg);
622         }
623         if (n_sent==0)
624           tr_err("tr_trpc_thread: notified of msg, but queue empty");
625         else 
626           tr_debug("tr_trpc_thread: sent %d messages.", n_sent);
627       }
628     }
629   }
630
631   tr_debug("tr_trpc_thread: exiting.");
632   msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_DISCONNECTED, TR_MQ_PRIO_HIGH);
633   tr_mq_msg_set_payload(msg, (void *)trpc, NULL); /* do not pass a free routine */
634   if (msg==NULL)
635     tr_err("tr_trpc_thread: error allocating TR_MQ_MSG");
636   else
637     trps_mq_add(trps, msg);
638
639   trpc_mq_clear(trpc); /* clear any queued messages */
640
641   talloc_free(tmp_ctx);
642   return NULL;
643 }
644
645 /* convert an IDP realm into routing table entries. Outputs number in *n_routes */
646 static TRP_ROUTE **tr_make_local_routes(TALLOC_CTX *mem_ctx,
647                                          TR_IDP_REALM *realm,
648                                          char *trust_router,
649                                          size_t *n_routes)
650 {
651   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
652   TR_APC *comm=NULL;
653   TRP_ROUTE *new_entry=NULL;
654   TRP_ROUTE **entries=NULL;
655   size_t n_comms=0, ii=0;
656
657   *n_routes=0;
658
659   if ((realm==NULL) || (realm->origin!=TR_REALM_LOCAL))
660     goto cleanup;
661
662   /* count comms */
663   for (comm=realm->apcs, n_comms=0; comm!=NULL; comm=comm->next,n_comms++) {}
664
665   entries=talloc_array(tmp_ctx, TRP_ROUTE *, n_comms);
666   for (comm=realm->apcs,ii=0; comm!=NULL; comm=comm->next, ii++) {
667     new_entry=trp_route_new(entries);
668     if (new_entry==NULL) {
669       tr_crit("tr_make_local_routes: unable to allocate entry.");
670       talloc_free(entries);
671       goto cleanup;
672     }
673     trp_route_set_comm(new_entry, tr_dup_name(comm->id));
674     trp_route_set_realm(new_entry, tr_dup_name(realm->realm_id));
675     trp_route_set_peer(new_entry, tr_new_name("")); /* no peer, it's us */
676     trp_route_set_metric(new_entry, 0);
677     trp_route_set_trust_router(new_entry, tr_new_name(trust_router));
678     trp_route_set_next_hop(new_entry, tr_new_name(""));
679     trp_route_set_local(new_entry, 1);
680     entries[ii]=new_entry;
681   }
682
683   talloc_steal(mem_ctx, entries);
684   *n_routes=n_comms;
685  cleanup:
686   talloc_free(tmp_ctx);
687   return entries;
688 }
689
690 void tr_peer_status_change(TRP_PEER *peer, void *cookie)
691 {
692   TRPS_INSTANCE *trps=talloc_get_type_abort(cookie, TRPS_INSTANCE);
693
694   if (TRP_SUCCESS!=trps_wildcard_route_req(trps, trp_peer_get_servicename(peer)))
695     tr_err("tr_send_wildcard: error sending wildcard route request.");
696 }
697
698 /* starts a trpc thread to connect to server:port */
699 TRP_RC tr_trpc_initiate(TRPS_INSTANCE *trps, TRP_PEER *peer, struct event *ev)
700 {
701   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
702   TRPC_INSTANCE *trpc=NULL;
703   TRP_CONNECTION *conn=NULL;
704   struct trpc_thread_data *thread_data=NULL;
705   TRP_RC rc=TRP_ERROR;
706
707   tr_debug("tr_trpc_initiate entered");
708   trpc=trpc_new(tmp_ctx);
709   if (trpc==NULL) {
710     tr_crit("tr_trpc_initiate: could not allocate TRPC_INSTANCE.");
711     rc=TRP_NOMEM;
712     goto cleanup;
713   }
714   tr_debug("tr_trpc_initiate: allocated trpc");
715
716   conn=trp_connection_new(trpc);
717   if (conn==NULL) {
718     tr_crit("tr_trpc_initiate: could not allocate TRP_CONNECTION.");
719     rc=TRP_NOMEM;
720     goto cleanup;
721   }
722
723   trpc_set_conn(trpc, conn);
724   trpc_set_server(trpc, talloc_strdup(trpc, trp_peer_get_server(peer)));
725   trpc_set_port(trpc, trp_peer_get_port(peer));
726   trpc_set_gssname(trpc, trp_peer_dup_servicename(peer));
727   tr_debug("tr_trpc_initiate: allocated connection");
728   
729   /* start thread */
730   thread_data=talloc(trpc, struct trpc_thread_data);
731   if (thread_data==NULL) {
732     tr_crit("tr_trpc_initiate: could not allocate struct trpc_thread_data.");
733     rc=TRP_NOMEM;
734     goto cleanup;
735   }
736   thread_data->trpc=trpc;
737   thread_data->trps=trps;
738
739   trps_add_trpc(trps, trpc); /* must add before starting thread */
740   pthread_create(trp_connection_get_thread(conn), NULL, tr_trpc_thread, thread_data);
741
742   tr_debug("tr_trpc_initiate: started trpc thread");
743   rc=TRP_SUCCESS;
744
745  cleanup:
746   talloc_free(tmp_ctx);
747   return rc;
748 }
749
750 /* Add local routes to the route table. */
751 TRP_RC tr_add_local_routes(TRPS_INSTANCE *trps, TR_CFG *cfg)
752 {
753   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
754   TR_IDP_REALM *cur=NULL;
755   TRP_ROUTE **local_routes=NULL;
756   size_t n_routes=0;
757   size_t ii=0;
758   char *trust_router_name=talloc_asprintf(tmp_ctx, "%s:%d", cfg->internal->hostname, cfg->internal->trps_port);
759
760   /* determine our trust router name */
761   if (trust_router_name==NULL)
762     return TRP_NOMEM;
763
764   for (cur=cfg->ctable->idp_realms; cur!=NULL; cur=cur->next) {
765     local_routes=tr_make_local_routes(tmp_ctx, cur, trust_router_name, &n_routes);
766     for (ii=0; ii<n_routes; ii++)
767       trps_add_route(trps, local_routes[ii]);
768
769     talloc_free(local_routes);
770     local_routes=NULL;
771     n_routes=0;
772   }
773
774   talloc_free(tmp_ctx);
775   return TRP_SUCCESS;
776 }
777
778 /* decide how often to attempt to connect to a peer */
779 static int tr_conn_attempt_due(TRPS_INSTANCE *trps, TRP_PEER *peer, struct timespec *when)
780 {
781   return 1; /* currently make an attempt every cycle */
782 }
783
784 /* open missing connections to peers */
785 TRP_RC tr_connect_to_peers(TRPS_INSTANCE *trps, struct event *ev)
786 {
787   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
788   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
789   TRP_PEER *peer=NULL;
790   struct timespec curtime={0,0};
791   TRP_RC rc=TRP_ERROR;
792
793   if (clock_gettime(CLOCK_REALTIME, &curtime)) {
794     tr_err("tr_connect_to_peers: failed to read time.");
795     rc=TRP_CLOCKERR;
796     goto cleanup;
797   }
798
799   for (peer=trp_ptable_iter_first(iter, trps->ptable);
800        peer!=NULL;
801        peer=trp_ptable_iter_next(iter))
802   {
803     if (trps_find_trpc(trps, peer)==NULL) {
804       TR_NAME *label=trp_peer_get_label(peer);
805       tr_debug("tr_connect_to_peers: %.*s missing connection.",
806                label->len, label->buf);
807       /* has it been long enough since we last tried? */
808       if (tr_conn_attempt_due(trps, peer, &curtime)) {
809         trp_peer_set_last_conn_attempt(peer, &curtime); /* we are trying again now */
810         if (tr_trpc_initiate(trps, peer, ev)!=TRP_SUCCESS) {
811           tr_err("tr_connect_to_peers: unable to initiate TRP connection to %s:%u.",
812                  trp_peer_get_server(peer),
813                  trp_peer_get_port(peer));
814         } 
815       }
816     }
817   }
818   rc=TRP_SUCCESS;
819     
820 cleanup:
821   trp_ptable_iter_free(iter);
822   talloc_free(tmp_ctx);
823   return rc;
824 }
825
826
827 /* Called by the config manager after a change to the active configuration.
828  * Updates configuration of objects that do not know about the config manager. */
829 void tr_config_changed(TR_CFG *new_cfg, void *cookie)
830 {
831   TR_INSTANCE *tr=talloc_get_type_abort(cookie, TR_INSTANCE);
832   TRPS_INSTANCE *trps=tr->trps;
833
834   tr->cfgwatch->poll_interval.tv_sec=new_cfg->internal->cfg_poll_interval;
835   tr->cfgwatch->poll_interval.tv_usec=0;
836
837   tr->cfgwatch->settling_time.tv_sec=new_cfg->internal->cfg_settling_time;
838   tr->cfgwatch->settling_time.tv_usec=0;
839
840   trps_set_connect_interval(trps, new_cfg->internal->trp_connect_interval);
841   trps_set_update_interval(trps, new_cfg->internal->trp_update_interval);
842   trps_set_sweep_interval(trps, new_cfg->internal->trp_sweep_interval);
843   trps_set_ctable(trps, new_cfg->ctable);
844   trps_set_ptable(trps, new_cfg->peers);
845   trps_set_peer_status_callback(trps, tr_peer_status_change, (void *)trps);
846   trps_clear_rtable(trps); /* should we do this every time??? */
847   tr_add_local_routes(trps, new_cfg); /* should we do this every time??? */
848   trps_update_active_routes(trps); /* find new routes */
849   trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
850   tr_print_config(new_cfg);
851   tr_trps_print_route_table(trps, stderr);
852 }
853