Attempt to route TID requests using routing table. Unstable.
[trust_router.git] / tr / tr_trp.c
1 #include <stdio.h>
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 from 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 from %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: incoming connection from unknown peer (%s) lost.",
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 from %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: outgoing 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_servicename(trps, gssname);
251       if (peer==NULL)
252         tr_err("tr_trps_process_mq: outgoing connection to unknown peer (%s) lost.", 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     trps_mq_add(trps, msg); /* steals msg context */
546     msg=NULL;
547
548     while(1) {
549       cb_data.msg_ready=0;
550       pthread_cond_wait(&(cb_data.cond), &(cb_data.mutex));
551       /* verify the condition */
552       if (cb_data.msg_ready) {
553         msg=trpc_mq_pop(trpc);
554         if (msg==NULL) {
555           /* no message in the queue */
556           tr_err("tr_trpc_thread: notified of msg, but queue empty");
557           break;
558         }
559
560         msg_type=tr_mq_msg_get_message(msg);
561
562         if (0==strcmp(msg_type, TR_MQMSG_ABORT)) {
563           tr_mq_msg_free(msg);
564           break; /* exit loop */
565         }
566         else if (0==strcmp(msg_type, TR_MQMSG_TRPC_SEND)) {
567           encoded_msg=tr_mq_msg_get_payload(msg);
568           if (encoded_msg==NULL)
569             tr_notice("tr_trpc_thread: null outgoing TRP message.");
570           else {
571             rc = trpc_send_msg(trpc, encoded_msg);
572             if (rc!=TRP_SUCCESS) {
573               tr_notice("tr_trpc_thread: trpc_send_msg failed.");
574               tr_mq_msg_free(msg);
575               break;
576             }
577           }
578         }
579         else
580           tr_notice("tr_trpc_thread: unknown message '%s' received.", msg_type);
581
582         tr_mq_msg_free(msg);
583       }
584     }
585   }
586
587   tr_debug("tr_trpc_thread: exiting.");
588   msg=tr_mq_msg_new(tmp_ctx, TR_MQMSG_TRPC_DISCONNECTED, TR_MQ_PRIO_HIGH);
589   tr_mq_msg_set_payload(msg, (void *)trpc, NULL); /* do not pass a free routine */
590   if (msg==NULL)
591     tr_err("tr_trpc_thread: error allocating TR_MQ_MSG");
592   else
593     trps_mq_add(trps, msg);
594
595   trpc_mq_clear(trpc); /* clear any queued messages */
596
597   talloc_free(tmp_ctx);
598   return NULL;
599 }
600
601 /* convert an IDP realm into routing table entries. Outputs number in *n_routes */
602 static TRP_ROUTE **tr_make_local_routes(TALLOC_CTX *mem_ctx,
603                                          TR_IDP_REALM *realm,
604                                          char *trust_router,
605                                          size_t *n_routes)
606 {
607   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
608   TR_APC *comm=NULL;
609   TRP_ROUTE *new_entry=NULL;
610   TRP_ROUTE **entries=NULL;
611   size_t n_comms=0, ii=0;
612
613   *n_routes=0;
614
615   if ((realm==NULL) || (realm->origin!=TR_REALM_LOCAL))
616     goto cleanup;
617
618   /* count comms */
619   for (comm=realm->apcs, n_comms=0; comm!=NULL; comm=comm->next,n_comms++) {}
620
621   entries=talloc_array(tmp_ctx, TRP_ROUTE *, n_comms);
622   for (comm=realm->apcs,ii=0; comm!=NULL; comm=comm->next, ii++) {
623     new_entry=trp_route_new(entries);
624     if (new_entry==NULL) {
625       tr_crit("tr_make_local_routes: unable to allocate entry.");
626       talloc_free(entries);
627       goto cleanup;
628     }
629     trp_route_set_comm(new_entry, tr_dup_name(comm->id));
630     trp_route_set_realm(new_entry, tr_dup_name(realm->realm_id));
631     trp_route_set_peer(new_entry, tr_new_name("")); /* no peer, it's us */
632     trp_route_set_metric(new_entry, 0);
633     trp_route_set_trust_router(new_entry, tr_new_name(trust_router));
634     trp_route_set_next_hop(new_entry, tr_new_name(""));
635     trp_route_set_local(new_entry, 1);
636     entries[ii]=new_entry;
637   }
638
639   talloc_steal(mem_ctx, entries);
640   *n_routes=n_comms;
641  cleanup:
642   talloc_free(tmp_ctx);
643   return entries;
644 }
645
646 void tr_peer_status_change(TRP_PEER *peer, void *cookie)
647 {
648   TRPS_INSTANCE *trps=talloc_get_type_abort(cookie, TRPS_INSTANCE);
649
650   if (TRP_SUCCESS!=trps_wildcard_route_req(trps, trp_peer_get_servicename(peer)))
651     tr_err("tr_send_wildcard: error sending wildcard route request.");
652 }
653
654 /* starts a trpc thread to connect to server:port */
655 TRP_RC tr_trpc_initiate(TRPS_INSTANCE *trps, TRP_PEER *peer, struct event *ev)
656 {
657   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
658   TRPC_INSTANCE *trpc=NULL;
659   TRP_CONNECTION *conn=NULL;
660   struct trpc_thread_data *thread_data=NULL;
661   TRP_RC rc=TRP_ERROR;
662
663   tr_debug("tr_trpc_initiate entered");
664   trpc=trpc_new(tmp_ctx);
665   if (trpc==NULL) {
666     tr_crit("tr_trpc_initiate: could not allocate TRPC_INSTANCE.");
667     rc=TRP_NOMEM;
668     goto cleanup;
669   }
670   tr_debug("tr_trpc_initiate: allocated trpc");
671
672   conn=trp_connection_new(trpc);
673   if (conn==NULL) {
674     tr_crit("tr_trpc_initiate: could not allocate TRP_CONNECTION.");
675     rc=TRP_NOMEM;
676     goto cleanup;
677   }
678
679   trpc_set_conn(trpc, conn);
680   trpc_set_server(trpc, talloc_strdup(trpc, trp_peer_get_server(peer)));
681   trpc_set_port(trpc, trp_peer_get_port(peer));
682   trpc_set_gssname(trpc, trp_peer_dup_servicename(peer));
683   tr_debug("tr_trpc_initiate: allocated connection");
684   
685   /* start thread */
686   thread_data=talloc(trpc, struct trpc_thread_data);
687   if (thread_data==NULL) {
688     tr_crit("tr_trpc_initiate: could not allocate struct trpc_thread_data.");
689     rc=TRP_NOMEM;
690     goto cleanup;
691   }
692   thread_data->trpc=trpc;
693   thread_data->trps=trps;
694
695   trps_add_trpc(trps, trpc); /* must add before starting thread */
696   pthread_create(trp_connection_get_thread(conn), NULL, tr_trpc_thread, thread_data);
697
698   tr_debug("tr_trpc_initiate: started trpc thread");
699   rc=TRP_SUCCESS;
700
701  cleanup:
702   talloc_free(tmp_ctx);
703   return rc;
704 }
705
706 /* Add local routes to the route table. */
707 TRP_RC tr_add_local_routes(TRPS_INSTANCE *trps, TR_CFG *cfg)
708 {
709   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
710   TR_IDP_REALM *cur=NULL;
711   TRP_ROUTE **local_routes=NULL;
712   size_t n_routes=0;
713   size_t ii=0;
714   char *trust_router_name=talloc_asprintf(tmp_ctx, "%s:%d", cfg->internal->hostname, cfg->internal->trps_port);
715
716   /* determine our trust router name */
717   if (trust_router_name==NULL)
718     return TRP_NOMEM;
719
720   for (cur=cfg->idp_realms; cur!=NULL; cur=cur->next) {
721     local_routes=tr_make_local_routes(tmp_ctx, cur, trust_router_name, &n_routes);
722     for (ii=0; ii<n_routes; ii++)
723       trps_add_route(trps, local_routes[ii]);
724
725     talloc_free(local_routes);
726     local_routes=NULL;
727     n_routes=0;
728   }
729
730   talloc_free(tmp_ctx);
731   return TRP_SUCCESS;
732 }
733
734 /* decide how often to attempt to connect to a peer */
735 static int tr_conn_attempt_due(TRPS_INSTANCE *trps, TRP_PEER *peer, struct timespec *when)
736 {
737   return 1; /* currently make an attempt every cycle */
738 }
739
740 /* open missing connections to peers */
741 TRP_RC tr_connect_to_peers(TRPS_INSTANCE *trps, struct event *ev)
742 {
743   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
744   TRP_PTABLE_ITER *iter=trp_ptable_iter_new(tmp_ctx);
745   TRP_PEER *peer=NULL;
746   struct timespec curtime={0,0};
747   TRP_RC rc=TRP_ERROR;
748
749   if (clock_gettime(CLOCK_REALTIME, &curtime)) {
750     tr_err("tr_connect_to_peers: failed to read time.");
751     rc=TRP_CLOCKERR;
752     goto cleanup;
753   }
754
755   for (peer=trp_ptable_iter_first(iter, trps->ptable);
756        peer!=NULL;
757        peer=trp_ptable_iter_next(iter))
758   {
759     if (trps_find_trpc(trps, peer)==NULL) {
760       tr_debug("tr_connect_to_peers: %.*s missing connection.",
761                trp_peer_get_gssname(peer)->len, trp_peer_get_gssname(peer)->buf);
762       /* has it been long enough since we last tried? */
763       if (tr_conn_attempt_due(trps, peer, &curtime)) {
764         trp_peer_set_last_conn_attempt(peer, &curtime); /* we are trying again now */
765         if (tr_trpc_initiate(trps, peer, ev)!=TRP_SUCCESS) {
766           tr_err("tr_connect_to_peers: unable to initiate TRP connection to %s:%u.",
767                  trp_peer_get_server(peer),
768                  trp_peer_get_port(peer));
769         } 
770       }
771     }
772   }
773   rc=TRP_SUCCESS;
774     
775 cleanup:
776   trp_ptable_iter_free(iter);
777   talloc_free(tmp_ctx);
778   return rc;
779 }
780
781
782 /* Called by the config manager after a change to the active configuration.
783  * Updates configuration of objects that do not know about the config manager. */
784 void tr_config_changed(TR_CFG *new_cfg, void *cookie)
785 {
786   TR_INSTANCE *tr=talloc_get_type_abort(cookie, TR_INSTANCE);
787   TRPS_INSTANCE *trps=tr->trps;
788
789   tr->cfgwatch->poll_interval.tv_sec=new_cfg->internal->cfg_poll_interval;
790   tr->cfgwatch->poll_interval.tv_usec=0;
791
792   tr->cfgwatch->settling_time.tv_sec=new_cfg->internal->cfg_settling_time;
793   tr->cfgwatch->settling_time.tv_usec=0;
794
795   trps_set_connect_interval(trps, new_cfg->internal->trp_connect_interval);
796   trps_set_update_interval(trps, new_cfg->internal->trp_update_interval);
797   trps_set_sweep_interval(trps, new_cfg->internal->trp_sweep_interval);
798   trps_clear_rtable(trps); /* should we do this every time??? */
799   tr_add_local_routes(trps, new_cfg); /* should we do this every time??? */
800   trps_update_active_routes(trps); /* find new routes */
801   trps_update(trps, TRP_UPDATE_TRIGGERED); /* send any triggered routes */
802   tr_trps_print_route_table(trps, stderr);
803 }
804