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