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