Merge pull request #74 from painless-security/jennifer/set_realm_apcs
[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, TR_MQ_PRIO_NORMAL);
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, TR_MQ_PRIO_HIGH);
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, TR_MQ_PRIO_HIGH);
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 */
191
192     conn=trp_connection_accept(tmp_ctx, listener, gssname);
193     if (conn!=NULL) {
194       /* need to monitor this fd and trigger events when read becomes possible */
195       thread_data=talloc(conn, struct trps_thread_data);
196       if (thread_data==NULL) {
197         tr_err("tr_trps_event_cb: unable to allocate trps_thread_data");
198         goto cleanup;
199       }
200       thread_data->conn=conn;
201       thread_data->trps=trps;
202       trps_add_connection(trps, conn); /* remember the connection - this puts conn and the thread data in trps's talloc context */
203       pthread_create(trp_connection_get_thread(conn), NULL, tr_trps_thread, thread_data);
204     }
205   }
206
207  cleanup:
208   talloc_free(tmp_ctx);
209 }
210
211 static void tr_trps_cleanup_conn(TRPS_INSTANCE *trps, TRP_CONNECTION *conn)
212 {
213   /* everything belonging to the thread is in the TRP_CONNECTION
214    * associated with it */
215   tr_debug("tr_trps_cleanup_conn: freeing %p", conn);
216   pthread_join(*trp_connection_get_thread(conn), NULL);
217   trps_remove_connection(trps, conn);
218   trp_connection_free(conn);
219   tr_debug("tr_trps_cleanup_conn: deleted connection");
220 }
221
222 static void tr_trps_cleanup_trpc(TRPS_INSTANCE *trps, TRPC_INSTANCE *trpc)
223 {
224   TR_MQ_MSG *msg;
225
226   /* tell the trpc thread to exit */
227   msg = tr_mq_msg_new(NULL, TR_MQMSG_TRPC_EXIT_OK, TR_MQ_PRIO_NORMAL);
228   if (msg) {
229     tr_debug("tr_trps_cleanup_trpc: Notifying thread that it may now exit");
230     trpc_mq_add(trpc, msg);
231   } else {
232     tr_crit("tr_trps_cleanup_trpc: Unable to acknowledge disconnection, thread will probably never terminate");
233   }
234
235   pthread_join(*trp_connection_get_thread(trpc_get_conn(trpc)), NULL);
236   trps_remove_trpc(trps, trpc);
237   trpc_free(trpc);
238   tr_debug("tr_trps_cleanup_trpc: deleted connection");
239 }
240
241 /**
242  * Get a dynamically allocated string with a description of the route table.
243  * Caller must free the string using talloc_free().
244  *
245  * @param memctx talloc context for the string
246  * @param trps trps instance containing the route table
247  * @return pointer to the output, or NULL on error
248  */
249 static char *tr_trps_route_table_to_str(TALLOC_CTX *memctx, TRPS_INSTANCE *trps)
250 {
251   return trp_rtable_to_str(memctx, trps->rtable, " | ", NULL);
252 }
253
254 /**
255  * Get a dynamically allocated string with a description of the community table.
256  * Caller must free the string using talloc_free().
257  *
258  * @param memctx talloc context for the string
259  * @param trps trps instance containing the community table
260  * @return pointer to the output, or NULL on error
261  */
262 static char *tr_trps_comm_table_to_str(TALLOC_CTX *memctx, TRPS_INSTANCE *trps)
263 {
264   return tr_comm_table_to_str(memctx, trps->ctable);
265 }
266
267 /**
268  * Event handler to process TRP messages from connection threads. These
269  * are added to the message queue (mq) in tr_trps_msg_handler(), which
270  * runs in the other threads.
271  *
272  * @param socket Ignored
273  * @param event Ignored
274  * @param arg Pointer to the TRPS_INSTANCE
275  */
276 static void tr_trps_process_mq(int socket, short event, void *arg)
277 {
278   TRPS_INSTANCE *trps=talloc_get_type_abort(arg, TRPS_INSTANCE);
279   TR_MQ_MSG *msg=NULL;
280   const char *s=NULL;
281   TRP_PEER *peer = NULL;
282   char *tmp = NULL;
283
284   msg=trps_mq_pop(trps);
285   while (msg!=NULL) {
286     s=tr_mq_msg_get_message(msg);
287     if (0==strcmp(s, TR_MQMSG_TRPS_CONNECTED)) {
288       TR_NAME *peer_gssname=(TR_NAME *)tr_mq_msg_get_payload(msg);
289       peer=trps_get_peer_by_gssname(trps, peer_gssname); /* get the peer record */
290       tmp = tr_name_strdup(peer_gssname); /* get the name as a null-terminated string */
291       if (peer==NULL)
292         tr_err("tr_trps_process_mq: incoming connection from unknown peer (%s) reported.", tmp);
293       else {
294         trp_peer_set_incoming_status(peer, PEER_CONNECTED);
295         tr_err("tr_trps_process_mq: incoming connection from %s established.", tmp);
296       }
297       free(tmp);
298     }
299     else if (0==strcmp(s, TR_MQMSG_TRPS_DISCONNECTED)) {
300       TRP_CONNECTION *conn=talloc_get_type_abort(tr_mq_msg_get_payload(msg), TRP_CONNECTION);
301       TR_NAME *peer_gssname=trp_connection_get_peer(conn);
302       peer=trps_get_peer_by_gssname(trps, peer_gssname); /* get the peer record */
303       tmp = tr_name_strdup(peer_gssname); /* get the name as a null-terminated string */
304       if (peer==NULL) {
305         tr_err("tr_trps_process_mq: incoming connection from unknown peer (%.*s) lost.", tmp);
306       } else {
307         trp_peer_set_incoming_status(peer, PEER_DISCONNECTED);
308         tr_trps_cleanup_conn(trps, conn);
309         tr_err("tr_trps_process_mq: incoming connection from %s lost.", tmp);
310       }
311       free(tmp);
312     }
313     else if (0==strcmp(s, TR_MQMSG_TRPC_CONNECTED)) {
314       TR_NAME *svcname=(TR_NAME *)tr_mq_msg_get_payload(msg);
315       peer=trps_get_peer_by_servicename(trps, svcname);
316       tmp = tr_name_strdup(svcname);
317       if (peer==NULL)
318         tr_err("tr_trps_process_mq: outgoing connection to unknown peer (%s) reported.", tmp);
319       else {
320         trp_peer_set_outgoing_status(peer, PEER_CONNECTED);
321         tr_err("tr_trps_process_mq: outgoing connection to %s established.", tmp);
322       }
323       free(tmp);
324     }
325     else if (0==strcmp(s, TR_MQMSG_TRPC_DISCONNECTED)) {
326       /* The trpc connection died - see note above tr_trpc_thread() regarding the shutdown protocol.
327        * The EXIT_OK message is sent in tr_trps_cleanup_trpc(). */
328       TRPC_INSTANCE *trpc=talloc_get_type_abort(tr_mq_msg_get_payload(msg), TRPC_INSTANCE);
329       TR_NAME *svcname=trpc_get_gssname(trpc);
330       peer=trps_get_peer_by_servicename(trps, svcname);
331       tmp = tr_name_strdup(svcname);
332       if (peer==NULL)
333         tr_err("tr_trps_process_mq: outgoing connection to unknown peer (%s) lost.", tmp);
334       else {
335         trp_peer_set_outgoing_status(peer, PEER_DISCONNECTED);
336         tr_err("tr_trps_process_mq: outgoing connection to %s lost.", tmp);
337         tr_trps_cleanup_trpc(trps, trpc);
338       }
339       free(tmp);
340     }
341
342     else if (0==strcmp(s, TR_MQMSG_MSG_RECEIVED)) {
343       if (trps_handle_tr_msg(trps, tr_mq_msg_get_payload(msg))!=TRP_SUCCESS)
344         tr_notice("tr_trps_process_mq: error handling message.");
345     }
346     else
347       tr_notice("tr_trps_process_mq: unknown message '%s' received.", tr_mq_msg_get_message(msg));
348
349     tr_mq_msg_free(msg);
350     msg=trps_mq_pop(trps);
351   }
352 }
353
354 static void tr_trps_update(int listener, short event, void *arg)
355 {
356   struct tr_trps_event_cookie *cookie=talloc_get_type_abort(arg, struct tr_trps_event_cookie);
357   TRPS_INSTANCE *trps=cookie->trps;
358   struct event *ev=cookie->ev;
359
360   tr_debug("tr_trps_update: sending scheduled route/community updates.");
361   trps_update(trps, TRP_UPDATE_SCHEDULED);
362   event_add(ev, &(trps->update_interval));
363   tr_debug("tr_trps_update: update interval=%d", trps->update_interval.tv_sec);
364 }
365
366 static void tr_trps_sweep(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   char *table_str=NULL;
372
373   tr_debug("tr_trps_sweep: sweeping routes.");
374   trps_sweep_routes(trps);
375   tr_debug("tr_trps_sweep: sweeping communities.");
376   trps_sweep_ctable(trps);
377   table_str=tr_trps_route_table_to_str(NULL, trps);
378   if (table_str!=NULL) {
379     tr_debug(table_str);
380     talloc_free(table_str);
381   }
382
383   table_str=tr_trps_comm_table_to_str(NULL, trps);
384   if (table_str!=NULL) {
385     tr_debug(table_str);
386     talloc_free(table_str);
387   }
388   /* schedule the event to run again */
389   event_add(ev, &(trps->sweep_interval));
390 }
391
392 static void tr_connection_update(int listener, short event, void *arg)
393 {
394   struct tr_trps_event_cookie *cookie=talloc_get_type_abort(arg, struct tr_trps_event_cookie);
395   TRPS_INSTANCE *trps=cookie->trps;
396   struct event *ev=cookie->ev;
397
398   tr_debug("tr_connection_update: checking peer connections.");
399   tr_connect_to_peers(trps, ev);
400   /* schedule the event to run again */
401   event_add(ev, &(trps->connect_interval));
402 }
403
404 static int tr_trps_events_destructor(void *obj)
405 {
406   TR_TRPS_EVENTS *ev=talloc_get_type_abort(obj, TR_TRPS_EVENTS);
407   if (ev->mq_ev!=NULL)
408     event_free(ev->mq_ev);
409   if (ev->connect_ev!=NULL)
410     event_free(ev->connect_ev);
411   if (ev->update_ev!=NULL)
412     event_free(ev->update_ev);
413   if (ev->sweep_ev!=NULL)
414     event_free(ev->sweep_ev);
415   return 0;
416 }
417 static TR_TRPS_EVENTS *tr_trps_events_new(TALLOC_CTX *mem_ctx)
418 {
419   TR_TRPS_EVENTS *ev=talloc(mem_ctx, TR_TRPS_EVENTS);
420   if (ev!=NULL) {
421     ev->listen_ev=talloc(ev, struct tr_socket_event);
422     ev->mq_ev=NULL;
423     ev->connect_ev=NULL;
424     ev->update_ev=NULL;
425     ev->sweep_ev=NULL;
426     if (ev->listen_ev==NULL) {
427       talloc_free(ev);
428       ev=NULL;
429     } else {
430       talloc_set_destructor((void *)ev, tr_trps_events_destructor);
431     }
432   }
433   return ev;
434 }
435
436 static void tr_trps_events_free(TR_TRPS_EVENTS *ev)
437 {
438   talloc_free(ev);
439 }
440
441 /* Configure the trps instance and set up its event handler.
442  * Fills in trps_ev, which should be allocated by caller. */
443 TRP_RC tr_trps_event_init(struct event_base *base, TR_INSTANCE *tr)
444 {
445   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
446   struct tr_socket_event *listen_ev=NULL;
447   struct tr_trps_event_cookie *trps_cookie=NULL;
448   struct tr_trps_event_cookie *connection_cookie=NULL;
449   struct tr_trps_event_cookie *update_cookie=NULL;
450   struct tr_trps_event_cookie *sweep_cookie=NULL;
451   struct timeval zero_time={0,0};
452   TRP_RC retval=TRP_ERROR;
453   size_t ii=0;
454
455   if (tr->events != NULL) {
456     tr_notice("tr_trps_event_init: tr->events was not null. Freeing before reallocating..");
457     tr_trps_events_free(tr->events);
458   }
459
460   tr->events=tr_trps_events_new(tmp_ctx);
461   if (tr->events == NULL) {
462     tr_debug("tr_trps_event_init: unable to allocate event handles.");
463     retval=TRP_NOMEM;
464     goto cleanup;
465   }
466
467   /* get convenient handles */
468   listen_ev=tr->events->listen_ev;
469
470   /* Create the cookie for callbacks. It will end up part of the trps context, so it will
471    * be cleaned up when trps is freed by talloc_free. */
472   trps_cookie=talloc(tr->events, struct tr_trps_event_cookie);
473   if (trps_cookie == NULL) {
474     tr_debug("tr_trps_event_init: Unable to allocate trps_cookie.");
475     retval=TRP_NOMEM;
476     tr_trps_events_free(tr->events);
477     tr->events=NULL;
478     goto cleanup;
479   }
480   trps_cookie->trps=tr->trps;
481   trps_cookie->cfg_mgr=tr->cfg_mgr;
482
483   /* get a trps listener */
484   listen_ev->n_sock_fd=trps_get_listener(tr->trps,
485                                          tr_trps_msg_handler,
486                                          tr_trps_gss_handler,
487                                          tr->cfg_mgr->active->internal->hostname,
488                                          tr->cfg_mgr->active->internal->trps_port,
489                                          (void *)trps_cookie,
490                                          listen_ev->sock_fd,
491                                          TR_MAX_SOCKETS);
492   if (listen_ev->n_sock_fd==0) {
493     tr_crit("Error opening TRP server socket.");
494     retval=TRP_ERROR;
495     tr_trps_events_free(tr->events);
496     tr->events=NULL;
497     goto cleanup;
498   }
499
500   /* Set up events for the sockets */
501   for (ii=0; ii<listen_ev->n_sock_fd; ii++) {
502     listen_ev->ev[ii]=event_new(base,
503                                 listen_ev->sock_fd[ii],
504                                 EV_READ|EV_PERSIST,
505                                 tr_trps_event_cb,
506                                 (void *)(tr->trps));
507     event_add(listen_ev->ev[ii], NULL);
508   }
509   
510   /* now set up message queue processing event, only triggered by
511    * tr_trps_mq_cb() */
512   tr->events->mq_ev=event_new(base,
513                               0,
514                               EV_PERSIST,
515                               tr_trps_process_mq,
516                               (void *)(tr->trps));
517   tr_mq_set_notify_cb(tr->trps->mq, tr_trps_mq_cb, tr->events->mq_ev);
518
519   /* now set up the peer connection timer event */
520   connection_cookie=talloc(tr->events, struct tr_trps_event_cookie);
521   if (connection_cookie == NULL) {
522     tr_debug("tr_trps_event_init: Unable to allocate connection_cookie.");
523     retval=TRP_NOMEM;
524     tr_trps_events_free(tr->events);
525     tr->events=NULL;
526     goto cleanup;
527   }
528   connection_cookie->trps=tr->trps;
529   connection_cookie->cfg_mgr=tr->cfg_mgr;
530   tr->events->connect_ev=event_new(base, -1, EV_TIMEOUT, tr_connection_update, (void *)connection_cookie);
531   connection_cookie->ev=tr->events->connect_ev; /* in case it needs to frob the event */
532   /* The first time, do this immediately. Thereafter, it will retrigger every trps->connect_interval */
533   event_add(tr->events->connect_ev, &zero_time);
534
535   /* now set up the route update timer event */
536   update_cookie=talloc(tr->events, struct tr_trps_event_cookie);
537   if (update_cookie == NULL) {
538     tr_debug("tr_trps_event_init: Unable to allocate update_cookie.");
539     retval=TRP_NOMEM;
540     tr_trps_events_free(tr->events);
541     tr->events=NULL;
542     goto cleanup;
543   }
544   update_cookie->trps=tr->trps;
545   update_cookie->cfg_mgr=tr->cfg_mgr;
546   tr->events->update_ev=event_new(base, -1, EV_TIMEOUT, tr_trps_update, (void *)update_cookie);
547   update_cookie->ev=tr->events->update_ev; /* in case it needs to frob the event */
548   event_add(tr->events->update_ev, &(tr->trps->update_interval));
549
550   /* now set up the route table sweep timer event */
551   sweep_cookie=talloc(tr->events, struct tr_trps_event_cookie);
552   if (sweep_cookie == NULL) {
553     tr_debug("tr_trps_event_init: Unable to allocate sweep_cookie.");
554     retval=TRP_NOMEM;
555     tr_trps_events_free(tr->events);
556     tr->events=NULL;
557     goto cleanup;
558   }
559   sweep_cookie->trps=tr->trps;
560   sweep_cookie->cfg_mgr=tr->cfg_mgr;
561   tr->events->sweep_ev=event_new(base, -1, EV_TIMEOUT, tr_trps_sweep, (void *)sweep_cookie);
562   sweep_cookie->ev=tr->events->sweep_ev; /* in case it needs to frob the event */
563   event_add(tr->events->sweep_ev, &(tr->trps->sweep_interval));
564
565   talloc_steal(tr, tr->events);
566   retval=TRP_SUCCESS;
567
568 cleanup:
569   talloc_free(tmp_ctx);
570   return retval;
571 }
572
573
574 struct trpc_notify_cb_data {
575   int msg_ready;
576   pthread_cond_t cond;
577   pthread_mutex_t mutex;
578 };
579
580 static void tr_trpc_mq_cb(TR_MQ *mq, void *arg)
581 {
582   struct trpc_notify_cb_data *cb_data=(struct trpc_notify_cb_data *) arg;
583   pthread_mutex_lock(&(cb_data->mutex));
584   if (!cb_data->msg_ready) {
585     cb_data->msg_ready=1;
586     pthread_cond_signal(&(cb_data->cond));
587   }
588   pthread_mutex_unlock(&(cb_data->mutex));
589 }
590
591 /* data passed to thread */
592 struct trpc_thread_data {
593   TRPC_INSTANCE *trpc;
594   TRPS_INSTANCE *trps;
595 };
596
597 /**
598  * Returns when a message is ready
599  */
600 static void trpc_thread_wait_for_message(struct trpc_notify_cb_data *cb)
601 {
602   cb->msg_ready = 0;
603   do
604     pthread_cond_wait(&(cb->cond), &(cb->mutex));
605   while (!cb->msg_ready);
606 }
607
608 /**
609  * Thread for handling TRPC (outgoing) connections
610  *
611  * Locking protocol:
612  *
613  * This thread uses a mutex and condition variable to wait for incoming messages
614  * on its queue. The main thread interacts with these through the tr_trpc_mq_cb()
615  * callback. This callback is called by the TR_MQ whenever the queue goes from empty
616  * to non-empty. The callback locks the thread's mutex, then sets a msg_ready flag
617  * signals the condition variable, then unlocks the mutex.
618  *
619  * This thread waits for the condition variable to be signaled, then checks that the
620  * msg_ready flag has actually been set (pthreads does not guarantee against false
621  * wakes). If so, it holds the mutex lock while reading any messages in its queue and
622  * sending responses over the GSS connection. If it receives an ABORT message from
623  * the main thread (not currently used), or if sending the GSS message fails (which
624  * usually indicates that the connection has been lost), the thread begins the shutdown
625  * process. It still holds the mutex lock at the start of this process.
626  *
627  * This begins by setting trpc->shutting_down = 1, then sending a message to the
628  * TRPS (main) thread indicating that it has DISCONNECTED. It then releases the mutex
629  * and waits for more messages, again using the mutex and the condition variable. It
630  * ignores any except for an EXIT_OK message. When that is received, it exits, terminating
631  * the thread.
632  *
633  * When the main thread receives the DISCONNECTED message, it must stop sending messages
634  * to this thread's message queue. When it is certain that it will not queue any more messages,
635  * it sends the EXIT_OK message as its last interaction with this thread. Once that message
636  * has been queued, queueing additional messages may result in deadlock or segfaults.
637  * (It is ok if there are other messages in the queue, but it must not queue more.)
638  */
639 static void *tr_trpc_thread(void *arg)
640 {
641   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
642   struct trpc_thread_data *thread_data=talloc_get_type_abort(arg, struct trpc_thread_data);
643   TRPC_INSTANCE *trpc=thread_data->trpc;
644   TRPS_INSTANCE *trps=thread_data->trps;
645   TRP_RC rc=TRP_ERROR;
646   TR_MQ_MSG *msg=NULL;
647   const char *msg_type=NULL;
648   char *encoded_msg=NULL;
649   TR_NAME *peer_gssname=NULL;
650   int n_sent = 0;
651   int n_popped = 0;
652   int exit_loop=0;
653
654   struct trpc_notify_cb_data cb_data={0,
655                                       PTHREAD_COND_INITIALIZER,
656                                       PTHREAD_MUTEX_INITIALIZER};
657
658   tr_debug("tr_trpc_thread: started");
659
660   /* set up the mq for receiving */
661   pthread_mutex_lock(&(cb_data.mutex)); /* hold this lock until we enter the main loop */
662
663   tr_mq_lock(trpc->mq);
664   tr_mq_set_notify_cb(trpc->mq, tr_trpc_mq_cb, (void *) &cb_data);
665   tr_mq_unlock(trpc->mq);
666
667   rc=trpc_connect(trpc);
668   if (rc!=TRP_SUCCESS) {
669     tr_notice("tr_trpc_thread: failed to initiate connection to %s:%d.",
670               trpc_get_server(trpc),
671               trpc_get_port(trpc));
672   } else {
673     peer_gssname=trp_connection_get_peer(trpc_get_conn(trpc));
674     if (peer_gssname==NULL) {
675       tr_err("tr_trpc_thread: could not duplicate peer_gssname.");
676       talloc_free(tmp_ctx);
677       return NULL;
678     }
679     tr_debug("tr_trpc_thread: connected to peer %s", peer_gssname->buf);
680
681     msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_CONNECTED, TR_MQ_PRIO_HIGH);
682     tr_mq_msg_set_payload(msg, (void *)tr_dup_name(peer_gssname), tr_free_name_helper);
683     if (msg==NULL) {
684       tr_err("tr_trpc_thread: error allocating TR_MQ_MSG");
685       talloc_free(tmp_ctx);
686       return NULL;
687     }
688     trps_mq_add(trps, msg); /* steals msg context */
689     msg=NULL;
690
691     while(!exit_loop) {
692       trpc_thread_wait_for_message(&cb_data); /* handles locking */
693
694       n_popped = 0; /* have not popped any messages from the queue */
695       n_sent = 0; /* have not sent any messages yet */
696       for (msg = trpc_mq_pop(trpc);
697            msg != NULL;
698            msg = trpc_mq_pop(trpc)) {
699         n_popped++;
700         msg_type = tr_mq_msg_get_message(msg);
701         if (0 == strcmp(msg_type, TR_MQMSG_ABORT)) {
702           exit_loop = 1;
703           break;
704         } else if (0 == strcmp(msg_type, TR_MQMSG_TRPC_SEND)) {
705           encoded_msg = tr_mq_msg_get_payload(msg);
706           if (encoded_msg == NULL)
707             tr_notice("tr_trpc_thread: null outgoing TRP message.");
708           else {
709             rc = trpc_send_msg(trpc, encoded_msg);
710             if (rc == TRP_SUCCESS) {
711               n_sent++;
712             } else {
713               tr_notice("tr_trpc_thread: trpc_send_msg failed.");
714               /* Assume this means we lost the connection. */
715               exit_loop = 1;
716               break;
717             }
718           }
719         } else
720           tr_notice("tr_trpc_thread: unknown message '%s' received.", msg_type);
721
722         tr_mq_msg_free(msg);
723       }
724
725       /* if n_popped == 0, then n_sent must be zero (it's only set after at
726        * least one msg is popped) */
727       if (n_popped==0)
728         tr_err("tr_trpc_thread: notified of message, but queue empty");
729       else
730         tr_debug("tr_trpc_thread: sent %d messages.", n_sent);
731     }
732   }
733
734   tr_debug("tr_trpc_thread: Disconnected. Waiting to terminate thread.");
735   trpc->shutting_down = 1;
736
737   /* Send a DISCONNECTED message to the main thread */
738   msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_DISCONNECTED, TR_MQ_PRIO_NORMAL);
739   tr_mq_msg_set_payload(msg, (void *)trpc, NULL); /* do not pass a free routine */
740   if (msg==NULL) {
741     /* can't notify main thread of exit - just do it and hope for the best */
742     tr_err("tr_trpc_thread: error allocating TR_MQ_MSG");
743   } else {
744     trps_mq_add(trps, msg);
745
746     /* DISCONNECTED sent, now wait for an acknowledgement before exiting */
747     exit_loop = 0;
748     while (!exit_loop) {
749       trpc_thread_wait_for_message(&cb_data);
750
751       while (NULL != (msg = trpc_mq_pop(trpc))) {
752         msg_type = tr_mq_msg_get_message(msg);
753
754         /* ignore anything except an EXIT_OK */
755         if (0 == strcmp(msg_type, TR_MQMSG_TRPC_EXIT_OK)) {
756           exit_loop = 1;
757           break; /* skip any further messages */
758         }
759       }
760     }
761   }
762
763   tr_debug("tr_trpc_thread: thread terminating.");
764   talloc_free(tmp_ctx);
765   return NULL;
766 }
767
768 /* convert an IDP realm into routing table entries. Outputs number in *n_routes */
769 static TRP_ROUTE **tr_make_local_routes(TALLOC_CTX *mem_ctx,
770                                          TR_IDP_REALM *realm,
771                                          char *trust_router,
772                                          size_t *n_routes)
773 {
774   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
775   TR_APC *comm=NULL;
776   TRP_ROUTE *new_entry=NULL;
777   TRP_ROUTE **entries=NULL;
778   size_t n_comms=0, ii=0;
779
780   *n_routes=0;
781
782   if ((realm==NULL) || (realm->origin!=TR_REALM_LOCAL))
783     goto cleanup;
784
785   /* count comms */
786   for (comm=realm->apcs, n_comms=0; comm!=NULL; comm=comm->next,n_comms++) {}
787
788   entries=talloc_array(tmp_ctx, TRP_ROUTE *, n_comms);
789   for (comm=realm->apcs,ii=0; comm!=NULL; comm=comm->next, ii++) {
790     new_entry=trp_route_new(entries);
791     if (new_entry==NULL) {
792       tr_crit("tr_make_local_routes: unable to allocate entry.");
793       talloc_free(entries);
794       goto cleanup;
795     }
796     trp_route_set_comm(new_entry, tr_dup_name(comm->id));
797     trp_route_set_realm(new_entry, tr_dup_name(realm->realm_id));
798     trp_route_set_peer(new_entry, tr_new_name("")); /* no peer, it's us */
799     trp_route_set_metric(new_entry, 0);
800     trp_route_set_trust_router(new_entry, tr_new_name(trust_router));
801     trp_route_set_next_hop(new_entry, tr_new_name(""));
802     trp_route_set_local(new_entry, 1);
803     entries[ii]=new_entry;
804   }
805
806   talloc_steal(mem_ctx, entries);
807   *n_routes=n_comms;
808  cleanup:
809   talloc_free(tmp_ctx);
810   return entries;
811 }
812
813 void tr_peer_status_change(TRP_PEER *peer, void *cookie)
814 {
815   TRPS_INSTANCE *trps=talloc_get_type_abort(cookie, TRPS_INSTANCE);
816
817   if (TRP_SUCCESS!=trps_wildcard_route_req(trps, trp_peer_get_servicename(peer)))
818     tr_err("tr_send_wildcard: error sending wildcard route request.");
819 }
820
821 /* starts a trpc thread to connect to server:port */
822 TRP_RC tr_trpc_initiate(TRPS_INSTANCE *trps, TRP_PEER *peer, struct event *ev)
823 {
824   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
825   TRPC_INSTANCE *trpc=NULL;
826   TRP_CONNECTION *conn=NULL;
827   struct trpc_thread_data *thread_data=NULL;
828   TRP_RC rc=TRP_ERROR;
829
830   tr_debug("tr_trpc_initiate entered");
831   trpc=trpc_new(tmp_ctx);
832   if (trpc==NULL) {
833     tr_crit("tr_trpc_initiate: could not allocate TRPC_INSTANCE.");
834     rc=TRP_NOMEM;
835     goto cleanup;
836   }
837   tr_debug("tr_trpc_initiate: allocated trpc");
838
839   conn=trp_connection_new(trpc);
840   if (conn==NULL) {
841     tr_crit("tr_trpc_initiate: could not allocate TRP_CONNECTION.");
842     rc=TRP_NOMEM;
843     goto cleanup;
844   }
845
846   trpc_set_conn(trpc, conn);
847   trpc_set_server(trpc, talloc_strdup(trpc, trp_peer_get_server(peer)));
848   trpc_set_port(trpc, trp_peer_get_port(peer));
849   trpc_set_gssname(trpc, trp_peer_dup_servicename(peer));
850   tr_debug("tr_trpc_initiate: allocated connection");
851   
852   /* start thread */
853   thread_data=talloc(trpc, struct trpc_thread_data);
854   if (thread_data==NULL) {
855     tr_crit("tr_trpc_initiate: could not allocate struct trpc_thread_data.");
856     rc=TRP_NOMEM;
857     goto cleanup;
858   }
859   thread_data->trpc=trpc;
860   thread_data->trps=trps;
861
862   trps_add_trpc(trps, trpc); /* must add before starting thread */
863   pthread_create(trp_connection_get_thread(conn), NULL, tr_trpc_thread, thread_data);
864
865   tr_debug("tr_trpc_initiate: started trpc thread");
866   rc=TRP_SUCCESS;
867
868  cleanup:
869   talloc_free(tmp_ctx);
870   return rc;
871 }
872
873 /* Add local routes to the route table. */
874 TRP_RC tr_add_local_routes(TRPS_INSTANCE *trps, TR_CFG *cfg)
875 {
876   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
877   TR_IDP_REALM *cur=NULL;
878   TRP_ROUTE **local_routes=NULL;
879   size_t n_routes=0;
880   size_t ii=0;
881   char *trust_router_name=talloc_asprintf(tmp_ctx, "%s:%d", cfg->internal->hostname, cfg->internal->trps_port);
882
883   /* determine our trust router name */
884   if (trust_router_name==NULL)
885     return TRP_NOMEM;
886
887   for (cur=cfg->ctable->idp_realms; cur!=NULL; cur=cur->next) {
888     local_routes=tr_make_local_routes(tmp_ctx, cur, trust_router_name, &n_routes);
889     for (ii=0; ii<n_routes; ii++)
890       trps_add_route(trps, local_routes[ii]);
891
892     talloc_free(local_routes);
893     local_routes=NULL;
894     n_routes=0;
895   }
896
897   talloc_free(tmp_ctx);
898   return TRP_SUCCESS;
899 }
900
901 /* decide how often to attempt to connect to a peer */
902 static int tr_conn_attempt_due(TRPS_INSTANCE *trps, TRP_PEER *peer, struct timespec *when)
903 {
904   return 1; /* currently make an attempt every cycle */
905 }
906
907 /* open missing connections to peers */
908 TRP_RC tr_connect_to_peers(TRPS_INSTANCE *trps, struct event *ev)
909 {
910   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
911   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
912   TRP_PEER *peer=NULL;
913   struct timespec curtime={0,0};
914   TRP_RC rc=TRP_ERROR;
915
916   if (clock_gettime(CLOCK_REALTIME, &curtime)) {
917     tr_err("tr_connect_to_peers: failed to read time.");
918     rc=TRP_CLOCKERR;
919     goto cleanup;
920   }
921
922   for (peer=trp_ptable_iter_first(iter, trps->ptable);
923        peer!=NULL;
924        peer=trp_ptable_iter_next(iter))
925   {
926     if (trps_find_trpc(trps, peer)==NULL) {
927       TR_NAME *label=trp_peer_get_label(peer);
928       tr_debug("tr_connect_to_peers: %.*s missing connection.",
929                label->len, label->buf);
930       /* has it been long enough since we last tried? */
931       if (tr_conn_attempt_due(trps, peer, &curtime)) {
932         trp_peer_set_last_conn_attempt(peer, &curtime); /* we are trying again now */
933         if (tr_trpc_initiate(trps, peer, ev)!=TRP_SUCCESS) {
934           tr_err("tr_connect_to_peers: unable to initiate TRP connection to %s:%u.",
935                  trp_peer_get_server(peer),
936                  trp_peer_get_port(peer));
937         } 
938       }
939     }
940   }
941   rc=TRP_SUCCESS;
942     
943 cleanup:
944   trp_ptable_iter_free(iter);
945   talloc_free(tmp_ctx);
946   return rc;
947 }
948
949
950 /* Called by the config manager after a change to the active configuration.
951  * Updates configuration of objects that do not know about the config manager. */
952 void tr_config_changed(TR_CFG *new_cfg, void *cookie)
953 {
954   TR_INSTANCE *tr=talloc_get_type_abort(cookie, TR_INSTANCE);
955   TRPS_INSTANCE *trps=tr->trps;
956   char *table_str=NULL;
957
958   tr->cfgwatch->poll_interval.tv_sec=new_cfg->internal->cfg_poll_interval;
959   tr->cfgwatch->poll_interval.tv_usec=0;
960
961   tr->cfgwatch->settling_time.tv_sec=new_cfg->internal->cfg_settling_time;
962   tr->cfgwatch->settling_time.tv_usec=0;
963
964   /* These need to be updated */
965   tr->tids->hostname = new_cfg->internal->hostname;
966   tr->mons->hostname = new_cfg->internal->hostname;
967
968   /* Update the authorized monitoring gss names */
969   if (tr->mons->authorized_gss_names) {
970     tr_debug("tr_config_changed: freeing tr->mons->authorized_gss_names");
971     tr_gss_names_free(tr->mons->authorized_gss_names);
972   }
973   if (new_cfg->internal->monitoring_credentials != NULL) {
974     tr->mons->authorized_gss_names = tr_gss_names_dup(tr->mons, new_cfg->internal->monitoring_credentials);
975   } else {
976     tr->mons->authorized_gss_names = tr_gss_names_new(tr->mons);
977   }
978   if (tr->mons->authorized_gss_names == NULL) {
979     tr_err("tr_config_changed: Error configuring monitoring credentials");
980   }
981
982   trps_set_connect_interval(trps, new_cfg->internal->trp_connect_interval);
983   trps_set_update_interval(trps, new_cfg->internal->trp_update_interval);
984   trps_set_sweep_interval(trps, new_cfg->internal->trp_sweep_interval);
985   trps_set_ctable(trps, new_cfg->ctable);
986   trps_set_ptable(trps, new_cfg->peers);
987   trps_set_peer_status_callback(trps, tr_peer_status_change, (void *)trps);
988   trps_clear_rtable(trps); /* should we do this every time??? */
989   tr_add_local_routes(trps, new_cfg); /* should we do this every time??? */
990   trps_update_active_routes(trps); /* find new routes */
991   trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
992   tr_print_config(new_cfg);
993   table_str=tr_trps_route_table_to_str(NULL, trps);
994   if (table_str!=NULL) {
995     tr_info(table_str);
996     talloc_free(table_str);
997   }
998   table_str=tr_trps_comm_table_to_str(NULL, trps);
999   if (table_str!=NULL) {
1000     tr_info(table_str);
1001     talloc_free(table_str);
1002   }
1003 }
1004