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