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