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