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