Support multiple AAA servers. Compiles but untested.
[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   jstr = json_string(srvr->aaa_server_addr);
322   json_object_set_new(jsrvr, "server_addr", jstr);
323
324   json_object_set_new(jsrvr,
325                       "key_expiration", json_string(time_str));
326   g_free(time_str);
327   /* Server DH Block */
328   jstr = json_string(srvr->key_name->buf);
329   json_object_set_new(jsrvr, "key_name", jstr);
330   json_object_set_new(jsrvr, "server_dh", tr_msg_encode_dh(srvr->aaa_server_dh));
331   if (srvr->path)
332     /* The path is owned by the srvr, so grab an extra ref*/
333     json_object_set(jsrvr, "path", srvr->path);
334   return jsrvr;
335 }
336
337 static int tr_msg_decode_one_server(json_t *jsrvr, TID_SRVR_BLK *srvr) 
338 {
339   json_t *jsrvr_addr = NULL;
340   json_t *jsrvr_kn = NULL;
341   json_t *jsrvr_dh = NULL;
342   json_t *jsrvr_expire = NULL;
343
344   if (jsrvr == NULL)
345     return -1;
346
347
348   if ((NULL == (jsrvr_addr = json_object_get(jsrvr, "server_addr"))) ||
349       (NULL == (jsrvr_kn = json_object_get(jsrvr, "key_name"))) ||
350       (NULL == (jsrvr_dh = json_object_get(jsrvr, "server_dh")))) {
351     tr_notice("tr_msg_decode_one_server(): Error parsing required fields.");
352     return -1;
353   }
354
355   srvr->aaa_server_addr=talloc_strdup(srvr, json_string_value(jsrvr_addr));
356   srvr->key_name = tr_new_name((char *)json_string_value(jsrvr_kn));
357   srvr->aaa_server_dh = tr_msg_decode_dh(jsrvr_dh);
358   srvr->path = json_object_get(jsrvr, "path");
359   jsrvr_expire = json_object_get(jsrvr, "key_expiration");
360   if (jsrvr_expire && json_is_string(jsrvr_expire)) {
361     if (!g_time_val_from_iso8601(json_string_value(jsrvr_expire),
362                                  &srvr->key_expiration))
363       tr_notice("Key expiration %s cannot be parsed", json_string_value(jsrvr_expire));
364   }
365   
366   return 0;
367 }
368
369 static json_t *tr_msg_encode_servers(TID_RESP *resp)
370 {
371   json_t *jservers = NULL;
372   json_t *jsrvr = NULL;
373   TID_SRVR_BLK *srvr = NULL;
374   size_t index;
375
376   jservers = json_array();
377
378   tid_resp_servers_foreach(resp, srvr, index) {
379     if ((NULL == (jsrvr = tr_msg_encode_one_server(srvr))) ||
380         (-1 == json_array_append_new(jservers, jsrvr))) {
381       return NULL;
382     }
383   }
384
385   //  tr_debug("tr_msg_encode_servers(): servers contains:");
386   //  tr_debug("%s", json_dumps(jservers, 0));
387   return jservers;
388 }
389
390 static TID_SRVR_BLK *tr_msg_decode_servers(TALLOC_CTX *mem_ctx, json_t *jservers)
391 {
392   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
393   TID_SRVR_BLK *servers=NULL;
394   TID_SRVR_BLK *new_srvr=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     goto cleanup;
404   }
405
406   for (i = 0; i < num_servers; i++) {
407     jsrvr = json_array_get(jservers, i);
408
409     new_srvr=tid_srvr_blk_new(NULL);
410     if (new_srvr==NULL) {
411       servers=NULL; /* it's all in tmp_ctx, so we can just let go */
412       goto cleanup;
413     }
414     
415     if (0 != tr_msg_decode_one_server(jsrvr, new_srvr)) {
416       servers=NULL; /* it's all in tmp_ctx, so we can just let go */
417       goto cleanup;
418     }
419
420     tid_srvr_blk_add(servers, new_srvr);
421   }
422
423   talloc_steal(mem_ctx, servers);
424
425 cleanup:
426   talloc_free(tmp_ctx);
427   return servers;
428 }
429
430 static json_t * tr_msg_encode_tidresp(TID_RESP *resp)
431 {
432   json_t *jresp = NULL;
433   json_t *jstr = NULL;
434   json_t *jservers = NULL;
435
436   if ((!resp) || (!resp->rp_realm) || (!resp->realm) || !(resp->comm))
437     return NULL;
438
439   jresp = json_object();
440
441   if (TID_ERROR == resp->result) {
442     jstr = json_string("error");
443     json_object_set_new(jresp, "result", jstr);
444     if (resp->err_msg) {
445       jstr = json_string(resp->err_msg->buf);
446       json_object_set_new(jresp, "err_msg", jstr);
447     }
448   }
449   else {
450     jstr = json_string("success");
451     json_object_set_new(jresp, "result", jstr);
452   }
453
454   jstr = json_string(resp->rp_realm->buf);
455   json_object_set_new(jresp, "rp_realm", jstr);
456
457   jstr = json_string(resp->realm->buf);
458   json_object_set_new(jresp, "target_realm", jstr);
459
460   jstr = json_string(resp->comm->buf);
461   json_object_set_new(jresp, "comm", jstr);
462
463   if (resp->orig_coi) {
464     jstr = json_string(resp->orig_coi->buf);
465     json_object_set_new(jresp, "orig_coi", jstr);
466   }
467
468   if (NULL == resp->servers) {
469     tr_debug("tr_msg_encode_tidresp(): No servers to encode.");
470   }
471   else {
472     jservers = tr_msg_encode_servers(resp);
473     json_object_set_new(jresp, "servers", jservers);
474   }
475   if (resp->error_path)
476     json_object_set(jresp, "error_path", resp->error_path);
477   
478   
479   return jresp;
480 }
481
482 static TID_RESP *tr_msg_decode_tidresp(json_t *jresp)
483 {
484   TID_RESP *tresp = NULL;
485   json_t *jresult = NULL;
486   json_t *jrp_realm = NULL;
487   json_t *jrealm = NULL;
488   json_t *jcomm = NULL;
489   json_t *jorig_coi = NULL;
490   json_t *jservers = NULL;
491   json_t *jerr_msg = NULL;
492
493   if (!(tresp=tid_resp_new(NULL))) {
494     tr_crit("tr_msg_decode_tidresp(): Error allocating TID_RESP structure.");
495     return NULL;
496   }
497  
498
499   /* store required fields from response */
500   if ((NULL == (jresult = json_object_get(jresp, "result"))) ||
501       (!json_is_string(jresult)) ||
502       (NULL == (jrp_realm = json_object_get(jresp, "rp_realm"))) ||
503       (!json_is_string(jrp_realm)) ||
504       (NULL == (jrealm = json_object_get(jresp, "target_realm"))) ||
505       (!json_is_string(jrealm)) ||
506       (NULL == (jcomm = json_object_get(jresp, "comm"))) ||
507       (!json_is_string(jcomm))) {
508     tr_debug("tr_msg_decode_tidresp(): Error parsing response.");
509     talloc_free(tresp);
510     return NULL;
511   }
512
513   if (0 == (strcmp(json_string_value(jresult), "success"))) {
514     tr_debug("tr_msg_decode_tidresp(): Success! result = %s.", json_string_value(jresult));
515     if ((NULL != (jservers = json_object_get(jresp, "servers"))) ||
516         (!json_is_array(jservers))) {
517       tresp->servers = tr_msg_decode_servers(tresp, jservers); 
518     } 
519     else {
520       talloc_free(tresp);
521       return NULL;
522     }
523     tresp->result = TID_SUCCESS;
524   }
525   else {
526     tresp->result = TID_ERROR;
527     tr_debug("tr_msg_decode_tidresp(): Error! result = %s.", json_string_value(jresult));
528     if ((NULL != (jerr_msg = json_object_get(jresp, "err_msg"))) ||
529         (!json_is_string(jerr_msg))) {
530       tresp->err_msg = tr_new_name((char *)json_string_value(jerr_msg));
531     }
532   }
533
534   tresp->rp_realm = tr_new_name((char *)json_string_value(jrp_realm));
535   tresp->realm = tr_new_name((char *)json_string_value(jrealm));
536   tresp->comm = tr_new_name((char *)json_string_value(jcomm));
537
538   /* store optional "orig_coi" field */
539   if ((NULL != (jorig_coi = json_object_get(jresp, "orig_coi"))) &&
540       (!json_is_object(jorig_coi))) {
541     tresp->orig_coi = tr_new_name((char *)json_string_value(jorig_coi));
542   }
543      
544   return tresp;
545 }
546
547
548 /* Information records for TRP update msg 
549  * requires that jrec already be allocated */
550 static TRP_RC tr_msg_encode_inforec_route(json_t *jrec, TRP_INFOREC *rec)
551 {
552   json_t *jstr=NULL;
553   json_t *jint=NULL;
554   char *s=NULL;
555
556   if (rec==NULL)
557     return TRP_BADTYPE;
558
559   if (trp_inforec_get_trust_router(rec)==NULL)
560     return TRP_ERROR;
561
562   s=tr_name_strdup(trp_inforec_get_trust_router(rec));
563   if (s==NULL)
564     return TRP_NOMEM;
565   jstr=json_string(s);
566   free(s);s=NULL;
567   if(jstr==NULL)
568     return TRP_ERROR;
569   json_object_set_new(jrec, "trust_router", jstr);
570
571   jint=json_integer(trp_inforec_get_metric(rec));
572   if(jint==NULL)
573     return TRP_ERROR;
574   json_object_set_new(jrec, "metric", jint);
575
576   jint=json_integer(trp_inforec_get_interval(rec));
577   if(jint==NULL)
578     return TRP_ERROR;
579   json_object_set_new(jrec, "interval", jint);
580
581   return TRP_SUCCESS;
582 }
583
584 /* returns a json array */
585 static json_t *tr_msg_encode_apcs(TR_APC *apcs)
586 {
587   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
588   TR_APC_ITER *iter=tr_apc_iter_new(tmp_ctx);
589   TR_APC *apc=NULL;
590   json_t *jarray=NULL;
591   json_t *jid=NULL;
592
593   if (iter==NULL)
594     goto cleanup;
595
596   jarray=json_array();
597   if (jarray==NULL)
598     goto cleanup;
599
600   for (apc=tr_apc_iter_first(iter, apcs); apc!=NULL; apc=tr_apc_iter_next(iter)) {
601     jid=tr_name_to_json_string(tr_apc_get_id(apc));
602     if ((jid==NULL) || (json_array_append_new(jarray, jid)!=0)) {
603       json_decref(jarray);
604       jarray=NULL;
605       goto cleanup;
606     }
607   }
608   
609 cleanup:
610   talloc_free(tmp_ctx);
611   return jarray;
612 }
613
614 static TR_APC *tr_msg_decode_apcs(TALLOC_CTX *mem_ctx, json_t *jarray, TRP_RC *rc)
615 {
616   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
617   size_t ii=0;
618   TR_APC *apc_list=NULL;
619   TR_APC *new=NULL;
620   json_t *jstr=NULL;
621
622   *rc=TRP_ERROR;
623
624   for (ii=0; ii<json_array_size(jarray); ii++) {
625     jstr=json_array_get(jarray, ii);
626     new=tr_apc_new(tmp_ctx);
627     if ((jstr==NULL) || (new==NULL) || (!json_is_string(jstr))) {
628       apc_list=NULL; /* these are all in tmp_ctx, so they'll still get cleaned up */
629       goto cleanup;
630     }
631
632     tr_apc_set_id(new, tr_new_name(json_string_value(jstr)));
633     if (tr_apc_get_id(new)==NULL) {
634       apc_list=NULL; /* these are all in tmp_ctx, so they'll still get cleaned up */
635       goto cleanup;
636     }
637
638     tr_apc_add(apc_list, new);
639   }
640
641   *rc=TRP_SUCCESS;
642
643   if (apc_list!=NULL)
644     talloc_steal(mem_ctx, apc_list);
645
646 cleanup:
647   talloc_free(tmp_ctx);
648   return apc_list;
649 }
650
651 static TRP_RC tr_msg_encode_inforec_comm(json_t *jrec, TRP_INFOREC *rec)
652 {
653   json_t *jstr=NULL;
654   json_t *jint=NULL;
655   json_t *japcs=NULL;
656   const char *sconst=NULL;
657   TR_COMM_TYPE commtype=TR_COMM_UNKNOWN;
658
659   if (rec==NULL)
660     return TRP_BADTYPE;
661
662   commtype=trp_inforec_get_comm_type(rec);
663   if (commtype==TR_COMM_UNKNOWN) {
664     tr_notice("tr_msg_encode_inforec_comm: unknown community type.");
665     return TRP_ERROR;
666   }
667   sconst=tr_comm_type_to_str(commtype);
668   if (sconst==NULL)
669     return TRP_ERROR;
670   jstr=json_string(sconst);
671   if(jstr==NULL)
672     return TRP_ERROR;
673   json_object_set_new(jrec, "type", jstr);
674
675   sconst=tr_realm_role_to_str(trp_inforec_get_role(rec));
676   if (sconst==NULL) {
677     tr_notice("tr_msg_encode_inforec_comm: unknown realm role.");
678     return TRP_ERROR;
679   }
680   jstr=json_string(sconst);
681   if(jstr==NULL)
682     return TRP_ERROR;
683   json_object_set_new(jrec, "role", jstr);
684
685   japcs=tr_msg_encode_apcs(trp_inforec_get_apcs(rec));
686   if (japcs==NULL) {
687     tr_notice("tr_msg_encode_inforec_comm: error encoding APCs.");
688     return TRP_ERROR;
689   }
690   json_object_set_new(jrec, "apcs", japcs);
691   
692
693   if (trp_inforec_get_owner_realm(rec)!=NULL) {
694     jstr=tr_name_to_json_string(trp_inforec_get_owner_realm(rec));
695     if(jstr==NULL)
696       return TRP_ERROR;
697     json_object_set_new(jrec, "owner_realm", jstr);
698   }  
699
700   if (trp_inforec_get_owner_contact(rec)!=NULL) {
701     jstr=tr_name_to_json_string(trp_inforec_get_owner_contact(rec));
702     if(jstr==NULL)
703       return TRP_ERROR;
704     json_object_set_new(jrec, "owner_contact", jstr);
705   }  
706
707   json_object_set(jrec, "provenance", trp_inforec_get_provenance(rec));
708
709   jint=json_integer(trp_inforec_get_interval(rec));
710   if(jint==NULL)
711     return TRP_ERROR;
712   json_object_set_new(jrec, "interval", jint);
713
714   return TRP_SUCCESS;
715 }
716
717 static json_t *tr_msg_encode_inforec(TRP_INFOREC *rec)
718 {
719   json_t *jrec=NULL;
720   json_t *jstr=NULL;
721
722   if ((rec==NULL) || (trp_inforec_get_type(rec)==TRP_INFOREC_TYPE_UNKNOWN))
723     return NULL;
724
725   jrec=json_object();
726   if (jrec==NULL)
727     return NULL;
728
729   jstr=json_string(trp_inforec_type_to_string(trp_inforec_get_type(rec)));
730   if (jstr==NULL) {
731     json_decref(jrec);
732     return NULL;
733   }
734   json_object_set_new(jrec, "record_type", jstr);
735
736   switch (rec->type) {
737   case TRP_INFOREC_TYPE_ROUTE:
738     if (TRP_SUCCESS!=tr_msg_encode_inforec_route(jrec, rec)) {
739       json_decref(jrec);
740       return NULL;
741     }
742     break;
743   case TRP_INFOREC_TYPE_COMMUNITY:
744     if (TRP_SUCCESS!=tr_msg_encode_inforec_comm(jrec, rec)) {
745       json_decref(jrec);
746       return NULL;
747     }
748     break;
749   default:
750     json_decref(jrec);
751     return NULL;
752   }
753   return jrec;
754 }
755
756 static TRP_RC tr_msg_decode_trp_inforec_route(json_t *jrecord, TRP_INFOREC *rec)
757 {
758   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
759   TRP_RC rc=TRP_ERROR;
760   char *s=NULL;
761   int num=0;
762
763   rc=tr_msg_get_json_string(jrecord, "trust_router", &s, tmp_ctx);
764   if (rc != TRP_SUCCESS)
765     goto cleanup;
766   if (TRP_SUCCESS!=trp_inforec_set_trust_router(rec, tr_new_name(s))) {
767     rc=TRP_ERROR;
768     goto cleanup;
769   }
770   talloc_free(s); s=NULL;
771
772   trp_inforec_set_next_hop(rec, NULL); /* make sure this is null (filled in later) */
773
774   rc=tr_msg_get_json_integer(jrecord, "metric", &num);
775   if ((rc != TRP_SUCCESS) || (TRP_SUCCESS!=trp_inforec_set_metric(rec,num)))
776     goto cleanup;
777
778   rc=tr_msg_get_json_integer(jrecord, "interval", &num);
779   if ((rc != TRP_SUCCESS) || (TRP_SUCCESS!=trp_inforec_set_interval(rec,num)))
780     goto cleanup;
781
782 cleanup:
783   talloc_free(tmp_ctx);
784   return rc;
785 }
786
787 static TRP_RC tr_msg_decode_trp_inforec_comm(json_t *jrecord, TRP_INFOREC *rec)
788 {
789   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
790   TRP_RC rc=TRP_ERROR;
791   char *s=NULL;
792   int num=0;
793   TR_APC *apcs=NULL;
794
795   rc=tr_msg_get_json_string(jrecord, "type", &s, tmp_ctx);
796   if (rc != TRP_SUCCESS)
797     goto cleanup;
798   if (TRP_SUCCESS!=trp_inforec_set_comm_type(rec, tr_comm_type_from_str(s))) {
799     rc=TRP_ERROR;
800     goto cleanup;
801   }
802   talloc_free(s); s=NULL;
803
804   rc=tr_msg_get_json_string(jrecord, "role", &s, tmp_ctx);
805   if (rc != TRP_SUCCESS)
806     goto cleanup;
807   if (TRP_SUCCESS!=trp_inforec_set_role(rec, tr_realm_role_from_str(s))) {
808     rc=TRP_ERROR;
809     goto cleanup;
810   }
811   talloc_free(s); s=NULL;
812
813   apcs=tr_msg_decode_apcs(rec, json_object_get(jrecord, "apcs"), &rc);
814   if (rc!=TRP_SUCCESS) {
815     rc=TRP_ERROR;
816     goto cleanup;
817   }
818   trp_inforec_set_apcs(rec, apcs);
819
820   rc=tr_msg_get_json_integer(jrecord, "interval", &num);
821   tr_debug("tr_msg_decode_trp_inforec_comm: interval=%u", num);
822   if ((rc != TRP_SUCCESS) || (TRP_SUCCESS!=trp_inforec_set_interval(rec,num)))
823     goto cleanup;
824
825   trp_inforec_set_provenance(rec, json_object_get(jrecord, "provenance"));
826
827   /* optional */
828   rc=tr_msg_get_json_string(jrecord, "owner_realm", &s, tmp_ctx);
829   if (rc == TRP_SUCCESS) {
830     if (TRP_SUCCESS!=trp_inforec_set_owner_realm(rec, tr_new_name(s))) {
831       rc=TRP_ERROR;
832       goto cleanup;
833     }
834     if (s!=NULL) {
835       talloc_free(s);
836       s=NULL;
837     }
838   }
839
840   rc=tr_msg_get_json_string(jrecord, "owner_contact", &s, tmp_ctx);
841   if (rc == TRP_SUCCESS) {
842     if (TRP_SUCCESS!=trp_inforec_set_owner_contact(rec, tr_new_name(s))) {
843       rc=TRP_ERROR;
844       goto cleanup;
845     }
846     if (s!=NULL) {
847       talloc_free(s);
848       s=NULL;
849     }
850   }
851
852 cleanup:
853   talloc_free(tmp_ctx);
854   return rc;
855 }
856
857 /* decode a single record */
858 static TRP_INFOREC *tr_msg_decode_trp_inforec(TALLOC_CTX *mem_ctx, json_t *jrecord)
859 {
860   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
861   TRP_INFOREC_TYPE rectype;
862   TRP_INFOREC *rec=NULL;
863   TRP_RC rc=TRP_ERROR;
864   char *s=NULL;
865   
866   if (TRP_SUCCESS!=tr_msg_get_json_string(jrecord, "record_type", &s, tmp_ctx))
867     goto cleanup;
868
869   rectype=trp_inforec_type_from_string(s);
870   talloc_free(s); s=NULL;
871
872   rec=trp_inforec_new(tmp_ctx, rectype);
873   if (rec==NULL) {
874     rc=TRP_NOMEM;
875     goto cleanup;
876   }
877
878   tr_debug("tr_msg_decode_trp_inforec: '%s' record found.", trp_inforec_type_to_string(rec->type));
879
880   switch(trp_inforec_get_type(rec)) {
881   case TRP_INFOREC_TYPE_ROUTE:
882     rc=tr_msg_decode_trp_inforec_route(jrecord, rec);
883     break;
884   case TRP_INFOREC_TYPE_COMMUNITY:
885     rc=tr_msg_decode_trp_inforec_comm(jrecord, rec);
886     break;
887   default:
888     rc=TRP_UNSUPPORTED;
889     goto cleanup;
890   }
891
892   talloc_steal(mem_ctx, rec);
893   rc=TRP_SUCCESS;
894
895 cleanup:
896   if (rc != TRP_SUCCESS) {
897     trp_inforec_free(rec);
898     rec=NULL;
899   }
900   talloc_free(tmp_ctx);
901   return rec;
902 }
903
904 /* TRP update msg */
905 static json_t *tr_msg_encode_trp_upd(TRP_UPD *update)
906 {
907   json_t *jupdate=NULL;
908   json_t *jrecords=NULL;
909   json_t *jrec=NULL;
910   json_t *jstr=NULL;
911   TRP_INFOREC *rec;
912   char *s=NULL;
913
914   if (update==NULL)
915     return NULL;
916
917   jupdate=json_object();
918   if (jupdate==NULL)
919     return NULL;
920
921   s=tr_name_strdup(trp_upd_get_comm(update));
922   if (s==NULL) {
923     json_decref(jupdate);
924     return NULL;
925   }
926   jstr=json_string(s);
927   free(s);s=NULL;
928   if(jstr==NULL) {
929     json_decref(jupdate);
930     return NULL;
931   }
932   json_object_set_new(jupdate, "community", jstr);
933
934   s=tr_name_strdup(trp_upd_get_realm(update));
935   if (s==NULL) {
936     json_decref(jupdate);
937     return NULL;
938   }
939   jstr=json_string(s);
940   free(s);s=NULL;
941   if(jstr==NULL) {
942     json_decref(jupdate);
943     return NULL;
944   }
945   json_object_set_new(jupdate, "realm", jstr);
946
947   jrecords=json_array();
948   if (jrecords==NULL) {
949     json_decref(jupdate);
950     return NULL;
951   }
952   json_object_set_new(jupdate, "records", jrecords); /* jrecords now a "borrowed" reference */
953   for (rec=trp_upd_get_inforec(update); rec!=NULL; rec=trp_inforec_get_next(rec)) {
954     tr_debug("tr_msg_encode_trp_upd: encoding inforec.");
955     jrec=tr_msg_encode_inforec(rec);
956     if (jrec==NULL) {
957       json_decref(jupdate); /* also decs jrecords and any elements */
958       return NULL;
959     }
960     if (0!=json_array_append_new(jrecords, jrec)) {
961       json_decref(jupdate); /* also decs jrecords and any elements */
962       json_decref(jrec); /* this one did not get added so dec explicitly */
963       return NULL;
964     }
965   }
966
967   return jupdate;
968 }
969
970 /* Creates a linked list of records in the msg->body talloc context.
971  * An error will be returned if any unparseable records are encountered. 
972  */
973 static TRP_UPD *tr_msg_decode_trp_upd(TALLOC_CTX *mem_ctx, json_t *jupdate)
974 {
975   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
976   json_t *jrecords=NULL;
977   size_t ii=0;
978   TRP_UPD *update=NULL;
979   TRP_INFOREC *new_rec=NULL;
980   TRP_INFOREC *list_tail=NULL;
981   char *s=NULL;
982   TR_NAME *name;
983   TRP_RC rc=TRP_ERROR;
984
985   update=trp_upd_new(tmp_ctx);
986   if (update==NULL) {
987     rc=TRP_NOMEM;
988     goto cleanup;
989   }
990
991   rc=tr_msg_get_json_string(jupdate, "community", &s, tmp_ctx);
992   if (rc != TRP_SUCCESS) {
993     tr_debug("tr_msg_decode_trp_upd: no community in TRP update message.");
994     rc=TRP_NOPARSE;
995     goto cleanup;
996   }
997   name=tr_new_name(s);
998   if (name==NULL) {
999     tr_debug("tr_msg_decode_trp_upd: could not allocate community name.");
1000     rc=TRP_NOMEM;
1001     goto cleanup;
1002   }
1003   talloc_free(s); s=NULL;
1004   trp_upd_set_comm(update, name);
1005
1006   rc=tr_msg_get_json_string(jupdate, "realm", &s, tmp_ctx);
1007   if (rc != TRP_SUCCESS) {
1008     tr_debug("tr_msg_decode_trp_upd: no realm in TRP update message.");
1009     rc=TRP_NOPARSE;
1010     goto cleanup;
1011   }
1012   name=tr_new_name(s);
1013   if (name==NULL) {
1014     tr_debug("tr_msg_decode_trp_upd: could not allocate realm name.");
1015     rc=TRP_NOMEM;
1016     goto cleanup;
1017   }
1018   talloc_free(s); s=NULL;
1019   trp_upd_set_realm(update, name);
1020
1021   jrecords=json_object_get(jupdate, "records");
1022   if ((jrecords==NULL) || (!json_is_array(jrecords))) {
1023     rc=TRP_NOPARSE;
1024     goto cleanup;
1025   }
1026
1027   tr_debug("tr_msg_decode_trp_upd: found %d records", json_array_size(jrecords));
1028   /* process the array */
1029   for (ii=0; ii<json_array_size(jrecords); ii++) {
1030     new_rec=tr_msg_decode_trp_inforec(update, json_array_get(jrecords, ii));
1031     if (new_rec==NULL) {
1032       rc=TRP_NOPARSE;
1033       goto cleanup;
1034     }
1035
1036     if (list_tail==NULL)
1037       trp_upd_set_inforec(update, new_rec); /* first is a special case */
1038     else
1039       trp_inforec_set_next(list_tail, new_rec);
1040
1041     list_tail=new_rec;
1042   }
1043
1044   /* Succeeded. Move new allocations into the correct talloc context */
1045   talloc_steal(mem_ctx, update);
1046   rc=TRP_SUCCESS;
1047
1048 cleanup:
1049   talloc_free(tmp_ctx);
1050   if (rc!=TRP_SUCCESS)
1051     return NULL;
1052   return update;
1053 }
1054
1055 static json_t *tr_msg_encode_trp_req(TRP_REQ *req)
1056 {
1057   json_t *jbody=NULL;
1058   json_t *jstr=NULL;
1059   char *s=NULL;
1060
1061   if (req==NULL)
1062     return NULL;
1063
1064   jbody=json_object();
1065   if (jbody==NULL)
1066     return NULL;
1067
1068   if ((NULL==trp_req_get_comm(req))
1069      || (NULL==trp_req_get_realm(req))) {
1070     json_decref(jbody);
1071     return NULL;
1072   }
1073
1074   s=tr_name_strdup(trp_req_get_comm(req)); /* ensures null termination */
1075   if (s==NULL) {
1076     json_decref(jbody);
1077     return NULL;
1078   }
1079   jstr=json_string(s);
1080   free(s); s=NULL;
1081   if (jstr==NULL) {
1082     json_decref(jbody);
1083     return NULL;
1084   }
1085   json_object_set_new(jbody, "community", jstr);
1086     
1087   s=tr_name_strdup(trp_req_get_realm(req)); /* ensures null termination */
1088   if (s==NULL) {
1089     json_decref(jbody);
1090     return NULL;
1091   }
1092   jstr=json_string(s);
1093   free(s); s=NULL;
1094   if (jstr==NULL) {
1095     json_decref(jbody);
1096     return NULL;
1097   }
1098   json_object_set_new(jbody, "realm", jstr);
1099
1100   return jbody;
1101 }
1102
1103 static TRP_REQ *tr_msg_decode_trp_req(TALLOC_CTX *mem_ctx, json_t *jreq)
1104 {
1105   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1106   TRP_REQ *req=NULL;
1107   char *s=NULL;
1108   TRP_RC rc=TRP_ERROR;
1109
1110   /* check message type and body type for agreement */
1111   req=trp_req_new(tmp_ctx);
1112   if (req==NULL) {
1113     rc=TRP_NOMEM;
1114     goto cleanup;
1115   }
1116
1117   rc=tr_msg_get_json_string(jreq, "community", &s, tmp_ctx);
1118   if (rc!=TRP_SUCCESS)
1119     goto cleanup;
1120   trp_req_set_comm(req, tr_new_name(s));
1121   talloc_free(s); s=NULL;
1122
1123   rc=tr_msg_get_json_string(jreq, "realm", &s, tmp_ctx);
1124   if (rc!=TRP_SUCCESS)
1125     goto cleanup;
1126   trp_req_set_realm(req, tr_new_name(s));
1127   talloc_free(s); s=NULL;
1128
1129   rc=TRP_SUCCESS;
1130   talloc_steal(mem_ctx, req);
1131
1132 cleanup:
1133   talloc_free(tmp_ctx);
1134   if (rc!=TRP_SUCCESS)
1135     return NULL;
1136   return req;
1137 }
1138
1139 char *tr_msg_encode(TR_MSG *msg) 
1140 {
1141   json_t *jmsg=NULL;
1142   json_t *jmsg_type=NULL;
1143   char *encoded=NULL;
1144   TID_RESP *tidresp=NULL;
1145   TID_REQ *tidreq=NULL;
1146   TRP_UPD *trpupd=NULL;
1147   TRP_REQ *trpreq=NULL;
1148
1149   /* TBD -- add error handling */
1150   jmsg = json_object();
1151
1152   switch (msg->msg_type) 
1153     {
1154     case TID_REQUEST:
1155       jmsg_type = json_string("tid_request");
1156       json_object_set_new(jmsg, "msg_type", jmsg_type);
1157       tidreq=tr_msg_get_req(msg);
1158       json_object_set_new(jmsg, "msg_body", tr_msg_encode_tidreq(tidreq));
1159       break;
1160
1161     case TID_RESPONSE:
1162       jmsg_type = json_string("tid_response");
1163       json_object_set_new(jmsg, "msg_type", jmsg_type);
1164       tidresp=tr_msg_get_resp(msg);
1165       json_object_set_new(jmsg, "msg_body", tr_msg_encode_tidresp(tidresp));
1166       break;
1167
1168     case TRP_UPDATE:
1169       jmsg_type = json_string("trp_update");
1170       json_object_set_new(jmsg, "msg_type", jmsg_type);
1171       trpupd=tr_msg_get_trp_upd(msg);
1172       json_object_set_new(jmsg, "msg_body", tr_msg_encode_trp_upd(trpupd));
1173       break;
1174
1175     case TRP_REQUEST:
1176       jmsg_type = json_string("trp_request");
1177       json_object_set_new(jmsg, "msg_type", jmsg_type);
1178       trpreq=tr_msg_get_trp_req(msg);
1179       json_object_set_new(jmsg, "msg_body", tr_msg_encode_trp_req(trpreq));
1180       break;
1181
1182     default:
1183       json_decref(jmsg);
1184       return NULL;
1185     }
1186
1187   encoded=json_dumps(jmsg, 0);
1188   tr_debug("tr_msg_encode: outgoing msg=%s", encoded);
1189   json_decref(jmsg);
1190   return encoded;
1191 }
1192
1193 TR_MSG *tr_msg_decode(char *jbuf, size_t buflen)
1194 {
1195   TR_MSG *msg=NULL;
1196   json_t *jmsg = NULL;
1197   json_error_t rc;
1198   json_t *jtype=NULL;
1199   json_t *jbody=NULL;
1200   const char *mtype = NULL;
1201
1202   if (NULL == (jmsg = json_loadb(jbuf, buflen, JSON_DISABLE_EOF_CHECK, &rc))) {
1203     tr_debug("tr_msg_decode(): error loading object");
1204     return NULL;
1205   }
1206
1207   if (!(msg = malloc(sizeof(TR_MSG)))) {
1208     tr_debug("tr_msg_decode(): Error allocating TR_MSG structure.");
1209     json_decref(jmsg);
1210     return NULL;
1211   }
1212  
1213   memset(msg, 0, sizeof(TR_MSG));
1214
1215   if ((NULL == (jtype = json_object_get(jmsg, "msg_type"))) ||
1216       (NULL == (jbody = json_object_get(jmsg, "msg_body")))) {
1217     tr_debug("tr_msg_decode(): Error parsing message header.");
1218     json_decref(jmsg);
1219     tr_msg_free_decoded(msg);
1220     return NULL;
1221   }
1222
1223   mtype = json_string_value(jtype);
1224
1225   if (0 == strcmp(mtype, "tid_request")) {
1226     msg->msg_type = TID_REQUEST;
1227     tr_msg_set_req(msg, tr_msg_decode_tidreq(jbody));
1228   }
1229   else if (0 == strcmp(mtype, "tid_response")) {
1230     msg->msg_type = TID_RESPONSE;
1231     tr_msg_set_resp(msg, tr_msg_decode_tidresp(jbody));
1232   }
1233   else if (0 == strcmp(mtype, "trp_update")) {
1234     msg->msg_type = TRP_UPDATE;
1235     tr_msg_set_trp_upd(msg, tr_msg_decode_trp_upd(NULL, jbody)); /* null talloc context for now */
1236   }
1237   else if (0 == strcmp(mtype, "trp_request")) {
1238     msg->msg_type = TRP_UPDATE;
1239     tr_msg_set_trp_req(msg, tr_msg_decode_trp_req(NULL, jbody)); /* null talloc context for now */
1240   }
1241   else {
1242     msg->msg_type = TR_UNKNOWN;
1243     msg->msg_rep = NULL;
1244   }
1245   return msg;
1246 }
1247
1248 void tr_msg_free_encoded(char *jmsg)
1249 {
1250   if (jmsg)
1251     free (jmsg);
1252 }
1253
1254 void tr_msg_free_decoded(TR_MSG *msg)
1255 {
1256   if (msg) {
1257     switch (msg->msg_type) {
1258     case TID_REQUEST:
1259       tid_req_free(tr_msg_get_req(msg));
1260       break;
1261     case TID_RESPONSE:
1262       tid_resp_free(tr_msg_get_resp(msg));
1263       break;
1264     case TRP_UPDATE:
1265       trp_upd_free(tr_msg_get_trp_upd(msg));
1266       break;
1267     case TRP_REQUEST:
1268       trp_req_free(tr_msg_get_trp_req(msg));
1269     default:
1270       break;
1271     }
1272     free (msg);
1273   }
1274 }