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