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