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