Fix segfault issues. Comm updates now sent, but ignored.
[trust_router.git] / common / tr_msg.c
1 /*
2  * Copyright (c) 2012-2014 , 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 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
37 #include <string.h>
38 #include <openssl/dh.h>
39 #include <jansson.h>
40 #include <assert.h>
41 #include <talloc.h>
42
43
44 #include <tr_apc.h>
45 #include <tr_comm.h>
46 #include <tr_msg.h>
47 #include <trust_router/tr_name.h>
48 #include <trp_internal.h>
49 #include <trust_router/tr_constraint.h>
50 #include <tr_debug.h>
51
52 /* JSON helpers */
53 /* Read attribute attr from msg as an integer. Returns nonzero on error. */
54 static int tr_msg_get_json_integer(json_t *jmsg, const char *attr, int *dest)
55 {
56   json_t *obj;
57
58   obj=json_object_get(jmsg, attr);
59   if (obj == NULL) {
60     return -1;
61   }
62   /* check type */
63   if (!json_is_integer(obj)) {
64     return -1;
65   }
66
67   (*dest)=json_integer_value(obj);
68   return 0;
69 }
70
71 /* Read attribute attr from msg as a string. Copies string into mem_ctx context so jmsg can
72  * be destroyed safely. Returns nonzero on error. */
73 static TRP_RC tr_msg_get_json_string(json_t *jmsg, const char *attr, char **dest, TALLOC_CTX *mem_ctx)
74 {
75   json_t *obj;
76
77   obj=json_object_get(jmsg, attr);
78   if (obj == NULL)
79     return TRP_ERROR;
80
81   /* check type */
82   if (!json_is_string(obj))
83     return TRP_ERROR;
84
85   *dest=talloc_strdup(mem_ctx, json_string_value(obj));
86   if (*dest==NULL)
87     return TRP_ERROR;
88
89   return TRP_SUCCESS;
90 }
91
92 enum msg_type tr_msg_get_msg_type(TR_MSG *msg) 
93 {
94   return msg->msg_type;
95 }
96
97 void tr_msg_set_msg_type(TR_MSG *msg, enum msg_type type)
98 {
99   msg->msg_type = type;
100 }
101
102 TID_REQ *tr_msg_get_req(TR_MSG *msg)
103 {
104   if (msg->msg_type == TID_REQUEST)
105     return (TID_REQ *)msg->msg_rep;
106   return NULL;
107 }
108
109 void tr_msg_set_req(TR_MSG *msg, TID_REQ *req)
110 {
111   msg->msg_rep = req;
112   msg->msg_type = TID_REQUEST;
113 }
114
115 TID_RESP *tr_msg_get_resp(TR_MSG *msg)
116 {
117   if (msg->msg_type == TID_RESPONSE)
118     return (TID_RESP *)msg->msg_rep;
119   return NULL;
120 }
121
122 void tr_msg_set_resp(TR_MSG *msg, TID_RESP *resp)
123 {
124   msg->msg_rep = resp;
125   msg->msg_type = TID_RESPONSE;
126 }
127
128 TRP_UPD *tr_msg_get_trp_upd(TR_MSG *msg)
129 {
130   if (msg->msg_type == TRP_UPDATE)
131     return (TRP_UPD *)msg->msg_rep;
132   return NULL;
133 }
134
135 void tr_msg_set_trp_upd(TR_MSG *msg, TRP_UPD *update)
136 {
137   msg->msg_rep=update;
138   talloc_steal(NULL, update); /* should attach to msg, but TR_MSG not usually talloc'ed */
139   msg->msg_type=TRP_UPDATE;
140 }
141
142 TRP_REQ *tr_msg_get_trp_req(TR_MSG *msg)
143 {
144   if (msg->msg_type == TRP_REQUEST)
145     return (TRP_REQ *)msg->msg_rep;
146   return NULL;
147 }
148
149 void tr_msg_set_trp_req(TR_MSG *msg, TRP_REQ *req)
150 {
151   msg->msg_rep=req;
152   msg->msg_type=TRP_REQUEST;
153 }
154
155 static json_t *tr_msg_encode_dh(DH *dh)
156 {
157   json_t *jdh = NULL;
158   json_t *jbn = NULL;
159
160   if ((!dh) || (!dh->p) || (!dh->g) || (!dh->pub_key))
161     return NULL;
162
163   jdh = json_object();
164
165   jbn = json_string(BN_bn2hex(dh->p));
166   json_object_set_new(jdh, "dh_p", jbn);
167
168   jbn = json_string(BN_bn2hex(dh->g));
169   json_object_set_new(jdh, "dh_g", jbn);
170
171   jbn = json_string(BN_bn2hex(dh->pub_key));
172   json_object_set_new(jdh, "dh_pub_key", jbn);
173
174   return jdh;
175 }
176
177 static DH *tr_msg_decode_dh(json_t *jdh)
178 {
179   DH *dh = NULL;
180   json_t *jp = NULL;
181   json_t *jg = NULL;
182   json_t *jpub_key = NULL;
183
184   if (!(dh = malloc(sizeof(DH)))) {
185     tr_crit("tr_msg_decode_dh(): Error allocating DH structure.");
186     return NULL;
187   }
188  
189   memset(dh, 0, sizeof(DH));
190
191   /* store required fields from dh object */
192   if ((NULL == (jp = json_object_get(jdh, "dh_p"))) ||
193       (NULL == (jg = json_object_get(jdh, "dh_g"))) ||
194       (NULL == (jpub_key = json_object_get(jdh, "dh_pub_key")))) {
195     tr_debug("tr_msg_decode_dh(): Error parsing dh_info.");
196     free(dh);
197     return NULL;
198   }
199
200   BN_hex2bn(&(dh->p), json_string_value(jp));
201   BN_hex2bn(&(dh->g), json_string_value(jg));
202   BN_hex2bn(&(dh->pub_key), json_string_value(jpub_key));
203
204   return dh;
205 }
206
207 static json_t * tr_msg_encode_tidreq(TID_REQ *req)
208 {
209   json_t *jreq = NULL;
210   json_t *jstr = NULL;
211
212   if ((!req) || (!req->rp_realm) || (!req->realm) || !(req->comm))
213     return NULL;
214
215   assert(jreq = json_object());
216
217   jstr = json_string(req->rp_realm->buf);
218   json_object_set_new(jreq, "rp_realm", jstr);
219
220   jstr = json_string(req->realm->buf);
221   json_object_set_new(jreq, "target_realm", jstr);
222
223   jstr = json_string(req->comm->buf);
224   json_object_set_new(jreq, "community", jstr);
225   
226   if (req->orig_coi) {
227     jstr = json_string(req->orig_coi->buf);
228     json_object_set_new(jreq, "orig_coi", jstr);
229   }
230
231   json_object_set_new(jreq, "dh_info", tr_msg_encode_dh(req->tidc_dh));
232
233   if (req->cons)
234     json_object_set(jreq, "constraints", (json_t *) req->cons);
235
236   if (req->path)
237     json_object_set(jreq, "path", req->path);
238   if (req->expiration_interval)
239     json_object_set_new(jreq, "expiration_interval",
240                         json_integer(req->expiration_interval));
241   
242   return jreq;
243 }
244
245 static TID_REQ *tr_msg_decode_tidreq(json_t *jreq)
246 {
247   TID_REQ *treq = NULL;
248   json_t *jrp_realm = NULL;
249   json_t *jrealm = NULL;
250   json_t *jcomm = NULL;
251   json_t *jorig_coi = NULL;
252   json_t *jdh = NULL;
253   json_t *jpath = NULL;
254   json_t *jexpire_interval = NULL;
255
256   if (!(treq =tid_req_new())) {
257     tr_crit("tr_msg_decode_tidreq(): Error allocating TID_REQ structure.");
258     return NULL;
259   }
260  
261   /* store required fields from request */
262   if ((NULL == (jrp_realm = json_object_get(jreq, "rp_realm"))) ||
263       (NULL == (jrealm = json_object_get(jreq, "target_realm"))) ||
264       (NULL == (jcomm = json_object_get(jreq, "community")))) {
265     tr_notice("tr_msg_decode(): Error parsing required fields.");
266     tid_req_free(treq);
267     return NULL;
268   }
269
270   jpath = json_object_get(jreq, "path");
271   jexpire_interval = json_object_get(jreq, "expiration_interval");
272
273   treq->rp_realm = tr_new_name((char *)json_string_value(jrp_realm));
274   treq->realm = tr_new_name((char *)json_string_value(jrealm));
275   treq->comm = tr_new_name((char *)json_string_value(jcomm));
276
277   /* Get DH Info from the request */
278   if (NULL == (jdh = json_object_get(jreq, "dh_info"))) {
279     tr_debug("tr_msg_decode(): Error parsing dh_info.");
280     tid_req_free(treq);
281     return NULL;
282   }
283   treq->tidc_dh = tr_msg_decode_dh(jdh);
284
285   /* store optional "orig_coi" field */
286   if (NULL != (jorig_coi = json_object_get(jreq, "orig_coi"))) {
287     treq->orig_coi = tr_new_name((char *)json_string_value(jorig_coi));
288   }
289
290   treq->cons = (TR_CONSTRAINT_SET *) json_object_get(jreq, "constraints");
291   if (treq->cons) {
292     if (!tr_constraint_set_validate(treq->cons)) {
293       tr_debug("Constraint set validation failed");
294     tid_req_free(treq);
295     return NULL;
296     }
297     json_incref((json_t *) treq->cons);
298     tid_req_cleanup_json(treq, (json_t *) treq->cons);
299   }
300   if (jpath) {
301     json_incref(jpath);
302     treq->path = jpath;
303     tid_req_cleanup_json(treq, jpath);
304   }
305   if (jexpire_interval)
306     treq->expiration_interval = json_integer_value(jexpire_interval);
307   
308   return treq;
309 }
310
311 static json_t *tr_msg_encode_one_server(TID_SRVR_BLK *srvr)
312 {
313   json_t *jsrvr = NULL;
314   json_t *jstr = NULL;
315   gchar *time_str = g_time_val_to_iso8601(&srvr->key_expiration);
316
317   tr_debug("Encoding one server.");
318
319   jsrvr = json_object();
320
321   /* Server IP Address -- TBD handle IPv6 */
322   jstr = json_string(inet_ntoa(srvr->aaa_server_addr));
323   json_object_set_new(jsrvr, "server_addr", jstr);
324
325   json_object_set_new(jsrvr,
326                       "key_expiration", json_string(time_str));
327   g_free(time_str);
328   /* Server DH Block */
329   jstr = json_string(srvr->key_name->buf);
330   json_object_set_new(jsrvr, "key_name", jstr);
331   json_object_set_new(jsrvr, "server_dh", tr_msg_encode_dh(srvr->aaa_server_dh));
332   if (srvr->path)
333     /* The path is owned by the srvr, so grab an extra ref*/
334     json_object_set(jsrvr, "path", srvr->path);
335   return jsrvr;
336 }
337
338 static int tr_msg_decode_one_server(json_t *jsrvr, TID_SRVR_BLK *srvr) 
339 {
340   json_t *jsrvr_addr = NULL;
341   json_t *jsrvr_kn = NULL;
342   json_t *jsrvr_dh = NULL;
343   json_t *jsrvr_expire = NULL;
344
345   if (jsrvr == NULL)
346     return -1;
347
348
349   if ((NULL == (jsrvr_addr = json_object_get(jsrvr, "server_addr"))) ||
350       (NULL == (jsrvr_kn = json_object_get(jsrvr, "key_name"))) ||
351       (NULL == (jsrvr_dh = json_object_get(jsrvr, "server_dh")))) {
352     tr_notice("tr_msg_decode_one_server(): Error parsing required fields.");
353     return -1;
354   }
355   
356   /* TBD -- handle IPv6 Addresses */
357   inet_aton(json_string_value(jsrvr_addr), &(srvr->aaa_server_addr));
358   srvr->key_name = tr_new_name((char *)json_string_value(jsrvr_kn));
359   srvr->aaa_server_dh = tr_msg_decode_dh(jsrvr_dh);
360   srvr->path = json_object_get(jsrvr, "path");
361   jsrvr_expire = json_object_get(jsrvr, "key_expiration");
362   if (jsrvr_expire && json_is_string(jsrvr_expire)) {
363     if (!g_time_val_from_iso8601(json_string_value(jsrvr_expire),
364                                  &srvr->key_expiration))
365       tr_notice("Key expiration %s cannot be parsed", json_string_value(jsrvr_expire));
366   }
367   
368   return 0;
369 }
370
371 static json_t *tr_msg_encode_servers(TID_RESP *resp)
372 {
373   json_t *jservers = NULL;
374   json_t *jsrvr = NULL;
375   TID_SRVR_BLK *srvr = NULL;
376   size_t index;
377
378   jservers = json_array();
379
380   tid_resp_servers_foreach(resp, srvr, index) {
381     if ((NULL == (jsrvr = tr_msg_encode_one_server(srvr))) ||
382         (-1 == json_array_append_new(jservers, jsrvr))) {
383       return NULL;
384     }
385   }
386
387   //  tr_debug("tr_msg_encode_servers(): servers contains:");
388   //  tr_debug("%s", json_dumps(jservers, 0));
389   return jservers;
390 }
391
392 static TID_SRVR_BLK *tr_msg_decode_servers(void * ctx, json_t *jservers, size_t *out_len)
393 {
394   TID_SRVR_BLK *servers = NULL;
395   json_t *jsrvr;
396   size_t i, num_servers;
397
398   num_servers = json_array_size(jservers);
399   tr_debug("tr_msg_decode_servers(): Number of servers = %u.", (unsigned) num_servers);
400   
401   if (0 == num_servers) {
402     tr_debug("tr_msg_decode_servers(): Server array is empty."); 
403     return NULL;
404   }
405   servers = talloc_zero_array(ctx, TID_SRVR_BLK, num_servers);
406
407   for (i = 0; i < num_servers; i++) {
408     jsrvr = json_array_get(jservers, i);
409     if (0 != tr_msg_decode_one_server(jsrvr, &servers[i])) {
410       talloc_free(servers);
411       return NULL;
412     }
413
414
415   }
416   *out_len = num_servers;
417   return servers;
418 }
419
420 static json_t * tr_msg_encode_tidresp(TID_RESP *resp)
421 {
422   json_t *jresp = NULL;
423   json_t *jstr = NULL;
424   json_t *jservers = NULL;
425
426   if ((!resp) || (!resp->rp_realm) || (!resp->realm) || !(resp->comm))
427     return NULL;
428
429   jresp = json_object();
430
431   if (TID_ERROR == resp->result) {
432     jstr = json_string("error");
433     json_object_set_new(jresp, "result", jstr);
434     if (resp->err_msg) {
435       jstr = json_string(resp->err_msg->buf);
436       json_object_set_new(jresp, "err_msg", jstr);
437     }
438   }
439   else {
440     jstr = json_string("success");
441     json_object_set_new(jresp, "result", jstr);
442   }
443
444   jstr = json_string(resp->rp_realm->buf);
445   json_object_set_new(jresp, "rp_realm", jstr);
446
447   jstr = json_string(resp->realm->buf);
448   json_object_set_new(jresp, "target_realm", jstr);
449
450   jstr = json_string(resp->comm->buf);
451   json_object_set_new(jresp, "comm", jstr);
452
453   if (resp->orig_coi) {
454     jstr = json_string(resp->orig_coi->buf);
455     json_object_set_new(jresp, "orig_coi", jstr);
456   }
457
458   if (NULL == resp->servers) {
459     tr_debug("tr_msg_encode_tidresp(): No servers to encode.");
460   }
461   else {
462     jservers = tr_msg_encode_servers(resp);
463     json_object_set_new(jresp, "servers", jservers);
464   }
465   if (resp->error_path)
466     json_object_set(jresp, "error_path", resp->error_path);
467   
468   
469   return jresp;
470 }
471
472 static TID_RESP *tr_msg_decode_tidresp(json_t *jresp)
473 {
474   TID_RESP *tresp = NULL;
475   json_t *jresult = NULL;
476   json_t *jrp_realm = NULL;
477   json_t *jrealm = NULL;
478   json_t *jcomm = NULL;
479   json_t *jorig_coi = NULL;
480   json_t *jservers = NULL;
481   json_t *jerr_msg = NULL;
482
483   if (!(tresp=tid_resp_new(NULL))) {
484     tr_crit("tr_msg_decode_tidresp(): Error allocating TID_RESP structure.");
485     return NULL;
486   }
487  
488
489   /* store required fields from response */
490   if ((NULL == (jresult = json_object_get(jresp, "result"))) ||
491       (!json_is_string(jresult)) ||
492       (NULL == (jrp_realm = json_object_get(jresp, "rp_realm"))) ||
493       (!json_is_string(jrp_realm)) ||
494       (NULL == (jrealm = json_object_get(jresp, "target_realm"))) ||
495       (!json_is_string(jrealm)) ||
496       (NULL == (jcomm = json_object_get(jresp, "comm"))) ||
497       (!json_is_string(jcomm))) {
498     tr_debug("tr_msg_decode_tidresp(): Error parsing response.");
499     talloc_free(tresp);
500     return NULL;
501   }
502
503   if (0 == (strcmp(json_string_value(jresult), "success"))) {
504     tr_debug("tr_msg_decode_tidresp(): Success! result = %s.", json_string_value(jresult));
505     if ((NULL != (jservers = json_object_get(jresp, "servers"))) ||
506         (!json_is_array(jservers))) {
507       tresp->servers = tr_msg_decode_servers(tresp, jservers, &tresp->num_servers); 
508     } 
509     else {
510       talloc_free(tresp);
511       return NULL;
512     }
513     tresp->result = TID_SUCCESS;
514   }
515   else {
516     tresp->result = TID_ERROR;
517     tr_debug("tr_msg_decode_tidresp(): Error! result = %s.", json_string_value(jresult));
518     if ((NULL != (jerr_msg = json_object_get(jresp, "err_msg"))) ||
519         (!json_is_string(jerr_msg))) {
520       tresp->err_msg = tr_new_name((char *)json_string_value(jerr_msg));
521     }
522   }
523
524   tresp->rp_realm = tr_new_name((char *)json_string_value(jrp_realm));
525   tresp->realm = tr_new_name((char *)json_string_value(jrealm));
526   tresp->comm = tr_new_name((char *)json_string_value(jcomm));
527
528   /* store optional "orig_coi" field */
529   if ((NULL != (jorig_coi = json_object_get(jresp, "orig_coi"))) &&
530       (!json_is_object(jorig_coi))) {
531     tresp->orig_coi = tr_new_name((char *)json_string_value(jorig_coi));
532   }
533      
534   return tresp;
535 }
536
537
538 /* Information records for TRP update msg 
539  * requires that jrec already be allocated */
540 static TRP_RC tr_msg_encode_inforec_route(json_t *jrec, TRP_INFOREC *rec)
541 {
542   json_t *jstr=NULL;
543   json_t *jint=NULL;
544   char *s=NULL;
545
546   if (rec==NULL)
547     return TRP_BADTYPE;
548
549   if (trp_inforec_get_trust_router(rec)==NULL)
550     return TRP_ERROR;
551
552   s=tr_name_strdup(trp_inforec_get_trust_router(rec));
553   if (s==NULL)
554     return TRP_NOMEM;
555   jstr=json_string(s);
556   free(s);s=NULL;
557   if(jstr==NULL)
558     return TRP_ERROR;
559   json_object_set_new(jrec, "trust_router", jstr);
560
561   jint=json_integer(trp_inforec_get_metric(rec));
562   if(jint==NULL)
563     return TRP_ERROR;
564   json_object_set_new(jrec, "metric", jint);
565
566   jint=json_integer(trp_inforec_get_interval(rec));
567   if(jint==NULL)
568     return TRP_ERROR;
569   json_object_set_new(jrec, "interval", jint);
570
571   return TRP_SUCCESS;
572 }
573
574 /* returns a json array */
575 static json_t *tr_msg_encode_apcs(TR_APC *apcs)
576 {
577   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
578   TR_APC_ITER *iter=tr_apc_iter_new(tmp_ctx);
579   TR_APC *apc=NULL;
580   json_t *jarray=NULL;
581   json_t *jid=NULL;
582
583   if (iter==NULL)
584     goto cleanup;
585
586   jarray=json_array();
587   if (jarray==NULL)
588     goto cleanup;
589
590   for (apc=tr_apc_iter_first(iter, apcs); apc!=NULL; apc=tr_apc_iter_next(iter)) {
591     jid=tr_name_to_json_string(tr_apc_get_id(apc));
592     if ((jid==NULL) || (json_array_append_new(jarray, jid)!=0)) {
593       json_decref(jarray);
594       jarray=NULL;
595       goto cleanup;
596     }
597   }
598   
599 cleanup:
600   talloc_free(tmp_ctx);
601   return jarray;
602 }
603
604 static TR_APC *tr_msg_decode_apcs(TALLOC_CTX *mem_ctx, json_t *jarray, TRP_RC *rc)
605 {
606   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
607   size_t ii=0;
608   TR_APC *apc_list=NULL;
609   TR_APC *new=NULL;
610   json_t *jstr=NULL;
611
612   *rc=TRP_ERROR;
613
614   for (ii=0; ii<json_array_size(jarray); ii++) {
615     jstr=json_array_get(jarray, ii);
616     new=tr_apc_new(tmp_ctx);
617     if ((jstr==NULL) || (new==NULL) || (!json_is_string(jstr))) {
618       apc_list=NULL; /* these are all in tmp_ctx, so they'll still get cleaned up */
619       goto cleanup;
620     }
621
622     tr_apc_set_id(new, tr_new_name(json_string_value(jstr)));
623     if (tr_apc_get_id(new)==NULL) {
624       apc_list=NULL; /* these are all in tmp_ctx, so they'll still get cleaned up */
625       goto cleanup;
626     }
627
628     tr_apc_add(apc_list, new);
629   }
630
631   *rc=TRP_SUCCESS;
632
633   if (apc_list!=NULL)
634     talloc_steal(mem_ctx, apc_list);
635
636 cleanup:
637   talloc_free(tmp_ctx);
638   return apc_list;
639 }
640
641 static TRP_RC tr_msg_encode_inforec_comm(json_t *jrec, TRP_INFOREC *rec)
642 {
643   json_t *jstr=NULL;
644   json_t *jint=NULL;
645   json_t *japcs=NULL;
646   const char *sconst=NULL;
647   TR_COMM_TYPE commtype=TR_COMM_UNKNOWN;
648
649   if (rec==NULL)
650     return TRP_BADTYPE;
651
652   commtype=trp_inforec_get_comm_type(rec);
653   if (commtype==TR_COMM_UNKNOWN) {
654     tr_notice("tr_msg_encode_inforec_comm: unknown community type.");
655     return TRP_ERROR;
656   }
657   sconst=tr_comm_type_to_str(commtype);
658   if (sconst==NULL)
659     return TRP_ERROR;
660   jstr=json_string(sconst);
661   if(jstr==NULL)
662     return TRP_ERROR;
663   json_object_set_new(jrec, "type", jstr);
664
665   sconst=tr_realm_role_to_str(trp_inforec_get_role(rec));
666   if (sconst==NULL) {
667     tr_notice("tr_msg_encode_inforec_comm: unknown realm role.");
668     return TRP_ERROR;
669   }
670   jstr=json_string(sconst);
671   if(jstr==NULL)
672     return TRP_ERROR;
673   json_object_set_new(jrec, "role", jstr);
674
675   japcs=tr_msg_encode_apcs(trp_inforec_get_apcs(rec));
676   if (japcs==NULL) {
677     tr_notice("tr_msg_encode_inforec_comm: error encoding APCs.");
678     return TRP_ERROR;
679   }
680   json_object_set_new(jrec, "apcs", japcs);
681   
682
683   if (trp_inforec_get_owner_realm(rec)!=NULL) {
684     jstr=tr_name_to_json_string(trp_inforec_get_owner_realm(rec));
685     if(jstr==NULL)
686       return TRP_ERROR;
687     json_object_set_new(jrec, "owner_realm", jstr);
688   }  
689
690   if (trp_inforec_get_owner_contact(rec)!=NULL) {
691     jstr=tr_name_to_json_string(trp_inforec_get_owner_contact(rec));
692     if(jstr==NULL)
693       return TRP_ERROR;
694     json_object_set_new(jrec, "owner_contact", jstr);
695   }  
696
697   json_object_set(jrec, "provenance", trp_inforec_get_provenance(rec));
698
699   jint=json_integer(trp_inforec_get_interval(rec));
700   if(jint==NULL)
701     return TRP_ERROR;
702   json_object_set_new(jrec, "interval", jint);
703
704   return TRP_SUCCESS;
705 }
706
707 static json_t *tr_msg_encode_inforec(TRP_INFOREC *rec)
708 {
709   json_t *jrec=NULL;
710   json_t *jstr=NULL;
711
712   if ((rec==NULL) || (trp_inforec_get_type(rec)==TRP_INFOREC_TYPE_UNKNOWN))
713     return NULL;
714
715   jrec=json_object();
716   if (jrec==NULL)
717     return NULL;
718
719   jstr=json_string(trp_inforec_type_to_string(trp_inforec_get_type(rec)));
720   if (jstr==NULL) {
721     json_decref(jrec);
722     return NULL;
723   }
724   json_object_set_new(jrec, "record_type", jstr);
725
726   switch (rec->type) {
727   case TRP_INFOREC_TYPE_ROUTE:
728     if (TRP_SUCCESS!=tr_msg_encode_inforec_route(jrec, rec)) {
729       json_decref(jrec);
730       return NULL;
731     }
732     break;
733   case TRP_INFOREC_TYPE_COMMUNITY:
734     if (TRP_SUCCESS!=tr_msg_encode_inforec_comm(jrec, rec)) {
735       json_decref(jrec);
736       return NULL;
737     }
738     break;
739   default:
740     json_decref(jrec);
741     return NULL;
742   }
743   return jrec;
744 }
745
746 static TRP_RC tr_msg_decode_trp_inforec_route(json_t *jrecord, TRP_INFOREC *rec)
747 {
748   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
749   TRP_RC rc=TRP_ERROR;
750   char *s=NULL;
751   int num=0;
752
753   rc=tr_msg_get_json_string(jrecord, "trust_router", &s, tmp_ctx);
754   if (rc != TRP_SUCCESS)
755     goto cleanup;
756   if (TRP_SUCCESS!=trp_inforec_set_trust_router(rec, tr_new_name(s))) {
757     rc=TRP_ERROR;
758     goto cleanup;
759   }
760   talloc_free(s); s=NULL;
761
762   trp_inforec_set_next_hop(rec, NULL); /* make sure this is null (filled in later) */
763
764   rc=tr_msg_get_json_integer(jrecord, "metric", &num);
765   if ((rc != TRP_SUCCESS) || (TRP_SUCCESS!=trp_inforec_set_metric(rec,num)))
766     goto cleanup;
767
768   rc=tr_msg_get_json_integer(jrecord, "interval", &num);
769   if ((rc != TRP_SUCCESS) || (TRP_SUCCESS!=trp_inforec_set_interval(rec,num)))
770     goto cleanup;
771
772 cleanup:
773   talloc_free(tmp_ctx);
774   return rc;
775 }
776
777 static TRP_RC tr_msg_decode_trp_inforec_comm(json_t *jrecord, TRP_INFOREC *rec)
778 {
779   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
780   TRP_RC rc=TRP_ERROR;
781   char *s=NULL;
782   int num=0;
783   TR_APC *apcs=NULL;
784
785   rc=tr_msg_get_json_string(jrecord, "type", &s, tmp_ctx);
786   if (rc != TRP_SUCCESS)
787     goto cleanup;
788   if (TRP_SUCCESS!=trp_inforec_set_comm_type(rec, tr_comm_type_from_str(s))) {
789     rc=TRP_ERROR;
790     goto cleanup;
791   }
792   talloc_free(s); s=NULL;
793
794   rc=tr_msg_get_json_string(jrecord, "role", &s, tmp_ctx);
795   if (rc != TRP_SUCCESS)
796     goto cleanup;
797   if (TRP_SUCCESS!=trp_inforec_set_role(rec, tr_realm_role_from_str(s))) {
798     rc=TRP_ERROR;
799     goto cleanup;
800   }
801   talloc_free(s); s=NULL;
802
803   apcs=tr_msg_decode_apcs(rec, json_object_get(jrecord, "apcs"), &rc);
804   if (rc!=TRP_SUCCESS) {
805     rc=TRP_ERROR;
806     goto cleanup;
807   }
808   trp_inforec_set_apcs(rec, apcs);
809
810   rc=tr_msg_get_json_string(jrecord, "owner_realm", &s, tmp_ctx);
811   if (rc != TRP_SUCCESS)
812     goto cleanup;
813   if (TRP_SUCCESS!=trp_inforec_set_owner_realm(rec, tr_new_name(s))) {
814     rc=TRP_ERROR;
815     goto cleanup;
816   }
817   talloc_free(s); s=NULL;
818
819   rc=tr_msg_get_json_string(jrecord, "owner_contact", &s, tmp_ctx);
820   if (rc != TRP_SUCCESS)
821     goto cleanup;
822   if (TRP_SUCCESS!=trp_inforec_set_owner_contact(rec, tr_new_name(s))) {
823     rc=TRP_ERROR;
824     goto cleanup;
825   }
826   talloc_free(s); s=NULL;
827
828   trp_inforec_set_provenance(rec, json_object_get(jrecord, "provenance"));
829
830   rc=tr_msg_get_json_integer(jrecord, "interval", &num);
831   if ((rc != TRP_SUCCESS) || (TRP_SUCCESS!=trp_inforec_set_interval(rec,num)))
832     goto cleanup;
833
834 cleanup:
835   talloc_free(tmp_ctx);
836   return rc;
837 }
838
839 /* decode a single record */
840 static TRP_INFOREC *tr_msg_decode_trp_inforec(TALLOC_CTX *mem_ctx, json_t *jrecord)
841 {
842   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
843   TRP_INFOREC_TYPE rectype;
844   TRP_INFOREC *rec=NULL;
845   TRP_RC rc=TRP_ERROR;
846   char *s=NULL;
847   
848   if (TRP_SUCCESS!=tr_msg_get_json_string(jrecord, "record_type", &s, tmp_ctx))
849     goto cleanup;
850
851   rectype=trp_inforec_type_from_string(s);
852   talloc_free(s); s=NULL;
853
854   rec=trp_inforec_new(tmp_ctx, rectype);
855   if (rec==NULL) {
856     rc=TRP_NOMEM;
857     goto cleanup;
858   }
859
860   tr_debug("tr_msg_decode_trp_inforec: '%s' record found.", trp_inforec_type_to_string(rec->type));
861
862   switch(trp_inforec_get_type(rec)) {
863   case TRP_INFOREC_TYPE_ROUTE:
864     rc=tr_msg_decode_trp_inforec_route(jrecord, rec);
865     break;
866   case TRP_INFOREC_TYPE_COMMUNITY:
867     rc=tr_msg_decode_trp_inforec_comm(jrecord, rec);
868     break;
869   default:
870     rc=TRP_UNSUPPORTED;
871     goto cleanup;
872   }
873
874   talloc_steal(mem_ctx, rec);
875   rc=TRP_SUCCESS;
876
877 cleanup:
878   if (rc != TRP_SUCCESS) {
879     trp_inforec_free(rec);
880     rec=NULL;
881   }
882   talloc_free(tmp_ctx);
883   return rec;
884 }
885
886 /* TRP update msg */
887 static json_t *tr_msg_encode_trp_upd(TRP_UPD *update)
888 {
889   json_t *jupdate=NULL;
890   json_t *jrecords=NULL;
891   json_t *jrec=NULL;
892   json_t *jstr=NULL;
893   TRP_INFOREC *rec;
894   char *s=NULL;
895
896   if (update==NULL)
897     return NULL;
898
899   jupdate=json_object();
900   if (jupdate==NULL)
901     return NULL;
902
903   s=tr_name_strdup(trp_upd_get_comm(update));
904   if (s==NULL) {
905     json_decref(jupdate);
906     return NULL;
907   }
908   jstr=json_string(s);
909   free(s);s=NULL;
910   if(jstr==NULL) {
911     json_decref(jupdate);
912     return NULL;
913   }
914   json_object_set_new(jupdate, "community", jstr);
915
916   s=tr_name_strdup(trp_upd_get_realm(update));
917   if (s==NULL) {
918     json_decref(jupdate);
919     return NULL;
920   }
921   jstr=json_string(s);
922   free(s);s=NULL;
923   if(jstr==NULL) {
924     json_decref(jupdate);
925     return NULL;
926   }
927   json_object_set_new(jupdate, "realm", jstr);
928
929   jrecords=json_array();
930   if (jrecords==NULL) {
931     json_decref(jupdate);
932     return NULL;
933   }
934   json_object_set_new(jupdate, "records", jrecords); /* jrecords now a "borrowed" reference */
935   for (rec=trp_upd_get_inforec(update); rec!=NULL; rec=trp_inforec_get_next(rec)) {
936     tr_debug("tr_msg_encode_trp_upd: encoding inforec.");
937     jrec=tr_msg_encode_inforec(rec);
938     if (jrec==NULL) {
939       json_decref(jupdate); /* also decs jrecords and any elements */
940       return NULL;
941     }
942     if (0!=json_array_append_new(jrecords, jrec)) {
943       json_decref(jupdate); /* also decs jrecords and any elements */
944       json_decref(jrec); /* this one did not get added so dec explicitly */
945       return NULL;
946     }
947   }
948
949   return jupdate;
950 }
951
952 /* Creates a linked list of records in the msg->body talloc context.
953  * An error will be returned if any unparseable records are encountered. 
954  */
955 static TRP_UPD *tr_msg_decode_trp_upd(TALLOC_CTX *mem_ctx, json_t *jupdate)
956 {
957   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
958   json_t *jrecords=NULL;
959   size_t ii=0;
960   TRP_UPD *update=NULL;
961   TRP_INFOREC *new_rec=NULL;
962   TRP_INFOREC *list_tail=NULL;
963   char *s=NULL;
964   TR_NAME *name;
965   TRP_RC rc=TRP_ERROR;
966
967   update=trp_upd_new(tmp_ctx);
968   if (update==NULL) {
969     rc=TRP_NOMEM;
970     goto cleanup;
971   }
972
973   rc=tr_msg_get_json_string(jupdate, "community", &s, tmp_ctx);
974   if (rc != TRP_SUCCESS) {
975     tr_debug("tr_msg_decode_trp_upd: no community in TRP update message.");
976     rc=TRP_NOPARSE;
977     goto cleanup;
978   }
979   name=tr_new_name(s);
980   if (name==NULL) {
981     tr_debug("tr_msg_decode_trp_upd: could not allocate community name.");
982     rc=TRP_NOMEM;
983     goto cleanup;
984   }
985   talloc_free(s); s=NULL;
986   trp_upd_set_comm(update, name);
987
988   rc=tr_msg_get_json_string(jupdate, "realm", &s, tmp_ctx);
989   if (rc != TRP_SUCCESS) {
990     tr_debug("tr_msg_decode_trp_upd: no realm in TRP update message.");
991     rc=TRP_NOPARSE;
992     goto cleanup;
993   }
994   name=tr_new_name(s);
995   if (name==NULL) {
996     tr_debug("tr_msg_decode_trp_upd: could not allocate realm name.");
997     rc=TRP_NOMEM;
998     goto cleanup;
999   }
1000   talloc_free(s); s=NULL;
1001   trp_upd_set_realm(update, name);
1002
1003   jrecords=json_object_get(jupdate, "records");
1004   if ((jrecords==NULL) || (!json_is_array(jrecords))) {
1005     rc=TRP_NOPARSE;
1006     goto cleanup;
1007   }
1008
1009   tr_debug("tr_msg_decode_trp_upd: found %d records", json_array_size(jrecords));
1010   /* process the array */
1011   for (ii=0; ii<json_array_size(jrecords); ii++) {
1012     new_rec=tr_msg_decode_trp_inforec(update, json_array_get(jrecords, ii));
1013     if (new_rec==NULL) {
1014       rc=TRP_NOPARSE;
1015       goto cleanup;
1016     }
1017
1018     if (list_tail==NULL)
1019       trp_upd_set_inforec(update, new_rec); /* first is a special case */
1020     else
1021       trp_inforec_set_next(list_tail, new_rec);
1022
1023     list_tail=new_rec;
1024   }
1025
1026   /* Succeeded. Move new allocations into the correct talloc context */
1027   talloc_steal(mem_ctx, update);
1028   rc=TRP_SUCCESS;
1029
1030 cleanup:
1031   talloc_free(tmp_ctx);
1032   if (rc!=TRP_SUCCESS)
1033     return NULL;
1034   return update;
1035 }
1036
1037 static json_t *tr_msg_encode_trp_req(TRP_REQ *req)
1038 {
1039   json_t *jbody=NULL;
1040   json_t *jstr=NULL;
1041   char *s=NULL;
1042
1043   if (req==NULL)
1044     return NULL;
1045
1046   jbody=json_object();
1047   if (jbody==NULL)
1048     return NULL;
1049
1050   if ((NULL==trp_req_get_comm(req))
1051      || (NULL==trp_req_get_realm(req))) {
1052     json_decref(jbody);
1053     return NULL;
1054   }
1055
1056   s=tr_name_strdup(trp_req_get_comm(req)); /* ensures null termination */
1057   if (s==NULL) {
1058     json_decref(jbody);
1059     return NULL;
1060   }
1061   jstr=json_string(s);
1062   free(s); s=NULL;
1063   if (jstr==NULL) {
1064     json_decref(jbody);
1065     return NULL;
1066   }
1067   json_object_set_new(jbody, "community", jstr);
1068     
1069   s=tr_name_strdup(trp_req_get_realm(req)); /* ensures null termination */
1070   if (s==NULL) {
1071     json_decref(jbody);
1072     return NULL;
1073   }
1074   jstr=json_string(s);
1075   free(s); s=NULL;
1076   if (jstr==NULL) {
1077     json_decref(jbody);
1078     return NULL;
1079   }
1080   json_object_set_new(jbody, "realm", jstr);
1081
1082   return jbody;
1083 }
1084
1085 static TRP_REQ *tr_msg_decode_trp_req(TALLOC_CTX *mem_ctx, json_t *jreq)
1086 {
1087   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1088   TRP_REQ *req=NULL;
1089   char *s=NULL;
1090   TRP_RC rc=TRP_ERROR;
1091
1092   /* check message type and body type for agreement */
1093   req=trp_req_new(tmp_ctx);
1094   if (req==NULL) {
1095     rc=TRP_NOMEM;
1096     goto cleanup;
1097   }
1098
1099   rc=tr_msg_get_json_string(jreq, "community", &s, tmp_ctx);
1100   if (rc!=TRP_SUCCESS)
1101     goto cleanup;
1102   trp_req_set_comm(req, tr_new_name(s));
1103   talloc_free(s); s=NULL;
1104
1105   rc=tr_msg_get_json_string(jreq, "realm", &s, tmp_ctx);
1106   if (rc!=TRP_SUCCESS)
1107     goto cleanup;
1108   trp_req_set_realm(req, tr_new_name(s));
1109   talloc_free(s); s=NULL;
1110
1111   rc=TRP_SUCCESS;
1112   talloc_steal(mem_ctx, req);
1113
1114 cleanup:
1115   talloc_free(tmp_ctx);
1116   if (rc!=TRP_SUCCESS)
1117     return NULL;
1118   return req;
1119 }
1120
1121 char *tr_msg_encode(TR_MSG *msg) 
1122 {
1123   json_t *jmsg=NULL;
1124   json_t *jmsg_type=NULL;
1125   char *encoded=NULL;
1126   TID_RESP *tidresp=NULL;
1127   TID_REQ *tidreq=NULL;
1128   TRP_UPD *trpupd=NULL;
1129   TRP_REQ *trpreq=NULL;
1130
1131   /* TBD -- add error handling */
1132   jmsg = json_object();
1133
1134   switch (msg->msg_type) 
1135     {
1136     case TID_REQUEST:
1137       jmsg_type = json_string("tid_request");
1138       json_object_set_new(jmsg, "msg_type", jmsg_type);
1139       tidreq=tr_msg_get_req(msg);
1140       json_object_set_new(jmsg, "msg_body", tr_msg_encode_tidreq(tidreq));
1141       break;
1142
1143     case TID_RESPONSE:
1144       jmsg_type = json_string("tid_response");
1145       json_object_set_new(jmsg, "msg_type", jmsg_type);
1146       tidresp=tr_msg_get_resp(msg);
1147       json_object_set_new(jmsg, "msg_body", tr_msg_encode_tidresp(tidresp));
1148       break;
1149
1150     case TRP_UPDATE:
1151       jmsg_type = json_string("trp_update");
1152       json_object_set_new(jmsg, "msg_type", jmsg_type);
1153       trpupd=tr_msg_get_trp_upd(msg);
1154       json_object_set_new(jmsg, "msg_body", tr_msg_encode_trp_upd(trpupd));
1155       break;
1156
1157     case TRP_REQUEST:
1158       jmsg_type = json_string("trp_request");
1159       json_object_set_new(jmsg, "msg_type", jmsg_type);
1160       trpreq=tr_msg_get_trp_req(msg);
1161       json_object_set_new(jmsg, "msg_body", tr_msg_encode_trp_req(trpreq));
1162       break;
1163
1164     default:
1165       json_decref(jmsg);
1166       return NULL;
1167     }
1168
1169   encoded=json_dumps(jmsg, 0);
1170   tr_debug("tr_msg_encode: outgoing msg=%s", encoded);
1171   json_decref(jmsg);
1172   return encoded;
1173 }
1174
1175 TR_MSG *tr_msg_decode(char *jbuf, size_t buflen)
1176 {
1177   TR_MSG *msg=NULL;
1178   json_t *jmsg = NULL;
1179   json_error_t rc;
1180   json_t *jtype=NULL;
1181   json_t *jbody=NULL;
1182   const char *mtype = NULL;
1183
1184   if (NULL == (jmsg = json_loadb(jbuf, buflen, JSON_DISABLE_EOF_CHECK, &rc))) {
1185     tr_debug("tr_msg_decode(): error loading object");
1186     return NULL;
1187   }
1188
1189   if (!(msg = malloc(sizeof(TR_MSG)))) {
1190     tr_debug("tr_msg_decode(): Error allocating TR_MSG structure.");
1191     json_decref(jmsg);
1192     return NULL;
1193   }
1194  
1195   memset(msg, 0, sizeof(TR_MSG));
1196
1197   if ((NULL == (jtype = json_object_get(jmsg, "msg_type"))) ||
1198       (NULL == (jbody = json_object_get(jmsg, "msg_body")))) {
1199     tr_debug("tr_msg_decode(): Error parsing message header.");
1200     json_decref(jmsg);
1201     tr_msg_free_decoded(msg);
1202     return NULL;
1203   }
1204
1205   mtype = json_string_value(jtype);
1206
1207   if (0 == strcmp(mtype, "tid_request")) {
1208     msg->msg_type = TID_REQUEST;
1209     tr_msg_set_req(msg, tr_msg_decode_tidreq(jbody));
1210   }
1211   else if (0 == strcmp(mtype, "tid_response")) {
1212     msg->msg_type = TID_RESPONSE;
1213     tr_msg_set_resp(msg, tr_msg_decode_tidresp(jbody));
1214   }
1215   else if (0 == strcmp(mtype, "trp_update")) {
1216     msg->msg_type = TRP_UPDATE;
1217     tr_msg_set_trp_upd(msg, tr_msg_decode_trp_upd(NULL, jbody)); /* null talloc context for now */
1218   }
1219   else if (0 == strcmp(mtype, "trp_request")) {
1220     msg->msg_type = TRP_UPDATE;
1221     tr_msg_set_trp_req(msg, tr_msg_decode_trp_req(NULL, jbody)); /* null talloc context for now */
1222   }
1223   else {
1224     msg->msg_type = TR_UNKNOWN;
1225     msg->msg_rep = NULL;
1226   }
1227   return msg;
1228 }
1229
1230 void tr_msg_free_encoded(char *jmsg)
1231 {
1232   if (jmsg)
1233     free (jmsg);
1234 }
1235
1236 void tr_msg_free_decoded(TR_MSG *msg)
1237 {
1238   if (msg) {
1239     switch (msg->msg_type) {
1240     case TID_REQUEST:
1241       tid_req_free(tr_msg_get_req(msg));
1242       break;
1243     case TID_RESPONSE:
1244       tid_resp_free(tr_msg_get_resp(msg));
1245       break;
1246     case TRP_UPDATE:
1247       trp_upd_free(tr_msg_get_trp_upd(msg));
1248       break;
1249     case TRP_REQUEST:
1250       trp_req_free(tr_msg_get_trp_req(msg));
1251     default:
1252       break;
1253     }
1254     free (msg);
1255   }
1256 }