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