91457581b3de270d0e8aa71164e83036e68a635d
[sip-router] / lib / binrpc / binrpc_api.c
1 /*
2  * Copyright (C) 2006 iptelorg GmbH
3  *
4  * This file is part of Kamailio, a free SIP server.
5  *
6  * Kamailio is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version
10  *
11  * Kamailio is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License 
17  * along with this program; if not, write to the Free Software 
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19  */
20  
21 /**
22  * send commands using binrpc
23  *
24  */
25
26 #include <sys/types.h>
27 #include <sys/uio.h>
28 #include <stdlib.h> /* realloc, rand ... */
29 #include <stdio.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <ctype.h> /* isprint */
33 #include <time.h> /* time */
34 /* #include <stropts.h>  - is this really needed? --andrei */
35
36 #include "../../modules/ctl/ctl_defaults.h" /* default socket & port */
37 #include "../../modules/ctl/init_socks.h"
38 #include "../../modules/ctl/binrpc.c" /* ugly hack */
39
40 #include "binrpc_api.h"
41
42
43 #define IOVEC_CNT 20
44 #define TEXT_BUFF_ALLOC_CHUNK   4096
45 #define FATAL_ERROR       -1
46
47 #ifndef NAME
48 #define NAME    "binrpc_api"
49 #endif
50
51 #define binrpc_malloc internal_malloc
52 #define binrpc_realloc internal_realloc
53 #define binrpc_free internal_free
54
55 #ifndef UNIX_PATH_MAX
56 #define UNIX_PATH_MAX 104
57 #endif
58
59 #ifndef INT2STR_MAX_LEN
60 #define INT2STR_MAX_LEN  (19+1+1) /* 2^64~= 16*10^18 => 19+1 digits + \0 */
61 #endif
62
63 static void* (*internal_malloc)(size_t size) = malloc;
64 static void* (*internal_realloc)(void* ptr, size_t size) = realloc;
65 static void (*internal_free)(void* ptr) = free;
66
67 static char binrpc_last_errs[1024] = "";
68 static int verbose = 0;
69
70 char *binrpc_get_last_errs() 
71 {
72     return binrpc_last_errs;
73 }
74
75 void binrpc_clear_last_err()
76 {
77     binrpc_last_errs[0] = '\0';
78 }
79
80 void binrpc_set_mallocs(void* _malloc, void* _realloc, void* _free)
81 {
82     internal_malloc = _malloc;
83     internal_realloc = _realloc;
84     internal_free = _free;
85 }
86
87 static int gen_cookie()
88 {
89         return rand();
90 }
91
92 static void hexdump(unsigned char* buf, int len, int ascii)
93 {
94         int r, i;
95         
96         /* dump it in hex */
97         for (r=0; r<len; r++){
98                 if ((r) && ((r%16)==0)){
99                         if (ascii){
100                                 putchar(' ');
101                                 for (i=r-16; i<r; i++){
102                                         if (isprint(buf[i]))
103                                                 putchar(buf[i]);
104                                         else
105                                                 putchar('.');
106                                 }
107                         }
108                         putchar('\n');
109                 }
110                 printf("%02x ", buf[r]);
111         };
112         if (ascii){
113                 for (i=r;i%16; i++)
114                         printf("   ");
115                 putchar(' ');
116                 for (i=16*(r/16); i<r; i++){
117                         if (isprint(buf[i]))
118                                 putchar(buf[i]);
119                         else
120                                 putchar('.');
121                 }
122         }
123         putchar('\n');
124 }
125
126 /* opens,  and  connects on a STREAM unix socket
127  * returns socket fd or -1 on error */
128 static int connect_unix_sock(char* name, int type, struct sockaddr_un* mysun,
129                       char* reply_socket, char* sock_dir)
130 {
131         struct sockaddr_un ifsun;
132         int s;
133         int len;
134         int ret;
135         int retries;    
136         
137         retries=0;
138         s=-1;
139         memset(&ifsun, 0, sizeof (struct sockaddr_un));
140         len=strlen(name);
141         if (len>UNIX_PATH_MAX){
142                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
143                                 "connect_unix_sock: name too long "
144                                 "(%d > %d): %s", len, UNIX_PATH_MAX, name);
145                 goto error;
146         }
147         ifsun.sun_family=AF_UNIX;
148         memcpy(ifsun.sun_path, name, len);
149 #ifdef HAVE_SOCKADDR_SA_LEN
150         ifsun.sun_len=len;
151 #endif
152         s=socket(PF_UNIX, type, 0);
153         if (s==-1){
154                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
155                         "connect_unix_sock: cannot create unix socket"
156                         " %s: %s [%d]", 
157                         name, strerror(errno), errno);
158                 goto error;
159         }
160         if (type==SOCK_DGRAM){
161                 /* we must bind so that we can receive replies */
162                 if (reply_socket==0){
163                         if (sock_dir==0)
164                                 sock_dir="/tmp";
165 retry:
166                         ret=snprintf(mysun->sun_path, UNIX_PATH_MAX, "%s/" NAME "_%d",
167                                                         sock_dir, rand()); 
168                         if ((ret<0) ||(ret>=UNIX_PATH_MAX)){
169                                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
170                                                         "connect_unix_sock: buffer overflow while trying to"
171                                                         "generate unix datagram socket name");
172                                 goto error;
173                         }
174                 }else{
175                         if (strlen(reply_socket)>UNIX_PATH_MAX){
176                                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
177                                                         "connect_unix_sock: buffer overflow while trying to"
178                                                         "use the provided unix datagram socket name (%s)",
179                                                         reply_socket);
180                                 goto error;
181                         }
182                         strcpy(mysun->sun_path, reply_socket);
183                 }
184                 mysun->sun_family=AF_UNIX;
185                 if (bind(s, (struct sockaddr*)&mysun, sizeof(struct sockaddr_un))==-1){
186                 //if (bind(s, mysun, sizeof(mysun))==-1){
187                         if (errno==EADDRINUSE && (reply_socket==0) && (retries < 10)){
188                                 retries++;
189                                 /* try another one */
190                                 goto retry;
191                         }
192                         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
193                                         "connect_unix_sock: could not bind the unix socket to"
194                                         " %s: %s (%d)",
195                                         mysun->sun_path, strerror(errno), errno);
196                         goto error;
197                 }
198         }
199         if (connect(s, (struct sockaddr *)&ifsun, sizeof(ifsun))==-1){
200                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
201                                 "connect_unix_sock: connect(%s): %s [%d]",
202                                 name, strerror(errno), errno);
203                 goto error;
204         }
205         return s;
206 error:
207         if (s!=-1) close(s);
208         return FATAL_ERROR;
209 }
210
211 static int connect_tcpudp_socket(char* address, int port, int type)
212 {
213         struct sockaddr_in addr;
214         struct hostent* he;
215         int sock;
216         
217         sock=-1;
218         /* resolve destination */
219         he=gethostbyname(address);
220         if (he==0){
221                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
222                                 "connect_tcpudp_socket: could not resolve %s", address);
223                 goto error;
224         }
225         /* open socket*/
226         addr.sin_family=he->h_addrtype;
227         addr.sin_port=htons(port);
228         memcpy(&addr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
229         
230         sock = socket(he->h_addrtype, type, 0);
231         if (sock==-1){
232                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
233                         "connect_tcpudp_socket: socket: %s", strerror(errno));
234                 goto error;
235         }
236         if (connect(sock, (struct sockaddr*) &addr, sizeof(struct sockaddr))!=0){
237                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
238                                 "connect_tcpudp_socket: connect: %s", strerror(errno));
239                 goto error;
240         }
241         return sock;
242 error:
243         if (sock!=-1) close(sock);
244         return FATAL_ERROR;
245 }
246
247 /* on exit cleanup */
248 static void cleanup(struct sockaddr_un* mysun)
249 {       
250         if (mysun->sun_path[0] != '\0') {
251                 if (unlink(mysun->sun_path) < 0) {
252                         fprintf(stderr, "ERROR: failed to delete %s: %s\n",
253                                         mysun->sun_path, strerror(errno));
254                 }
255         }
256 }
257
258 int binrpc_open_connection(struct binrpc_handle* handle, char* name, int port, int proto,
259                     char* reply_socket, char* sock_dir)
260 {
261         struct sockaddr_un mysun;
262                 
263         binrpc_last_errs[0] = '\0';
264         binrpc_last_errs[sizeof(binrpc_last_errs)-1] = '\0';  /* snprintf safe terminator */
265
266         handle->socket = -1;
267         handle->buf = NULL;
268         mysun.sun_path[0] = '\0';
269         
270         /* init the random number generator */
271         srand(getpid()+time(0)); /* we don't need very strong random numbers */
272         
273         if (name == NULL) {
274                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
275                         "open_connection: invalid IP address or socket name");
276                 goto error;
277         }
278         
279         handle->proto = proto;
280         switch(proto) {
281                 case UDP_SOCK:
282                 case TCP_SOCK:
283                         if (port == 0) {
284                                 port=DEFAULT_CTL_PORT;
285                         }
286                         
287                         handle->sock_type = (proto == UDP_SOCK) ? SOCK_DGRAM : SOCK_STREAM;
288                         if ((handle->socket = connect_tcpudp_socket(name, port, handle->sock_type)) < 0) {
289                                 goto error;
290                         }
291                         break;
292                 case UNIXS_SOCK:
293                 case UNIXD_SOCK:
294                         handle->sock_type = (proto == UNIXD_SOCK) ? SOCK_DGRAM : SOCK_STREAM;
295                         if ((handle->socket = connect_unix_sock(name, handle->sock_type, &mysun, reply_socket, sock_dir)) < 0) {
296                                 goto error;
297                         }
298                         break;
299                 case UNKNOWN_SOCK:
300                         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
301                                 "open_connection: Bad socket type for %s\n", name); /*vm zmenit*/
302                         goto error;
303         }
304         if (handle->sock_type == SOCK_DGRAM) {
305                 handle->buf_size = 8192;  /* max size of datagram, < SSIZE_MAX, TODO: does a platform dependent constant exist ? */
306         }
307         else {
308                 handle->buf_size = BINRPC_MAX_HDR_SIZE; 
309         }
310         handle->buf = binrpc_malloc(handle->buf_size);
311         if (!handle->buf) {
312                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
313                         "open_connection: not enough memory to allocate buffer. Needed %d bytes", handle->buf_size);    
314                 binrpc_close_connection(handle);
315         }
316         cleanup(&mysun);
317         return 0;
318         
319 error:
320         cleanup(&mysun);
321         return FATAL_ERROR;
322 }
323
324 int binrpc_open_connection_url(struct binrpc_handle* handle, char* url) {
325         static char name[100];
326         char *c, *c2, *rpl_sock;
327         int port, proto, i;
328         handle->socket = -1;
329         handle->buf = NULL;
330         /* parse proto:name:port|unixd_sock */
331         c = url;
332         if (strncasecmp(c, "udp:", 4) == 0)
333                 proto = UDP_SOCK;
334         else if (strncasecmp(c, "tcp:", 4) == 0)
335                 proto = TCP_SOCK;
336         else if (strncasecmp(c, "unix:", 5) == 0 || strncasecmp(c, "unixs:", 6) == 0)
337                 proto = UNIXS_SOCK;
338         else if (strncasecmp(c, "unixd:", 6) == 0)
339                 proto = UNIXD_SOCK;
340         else {
341                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
342                         "open_connection_url: bad protocol in '%s'", c);
343                 return FATAL_ERROR;     
344         }
345         while (*c != ':') c++;
346         c++;
347         c2 = strchr(c, ':');
348         if (!c2)
349                 c2 = c + strlen(c);
350         if (c2 - c > sizeof(name)-1) {
351                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
352                         "open_connection_url: name is too long '%s'", c);
353                 return FATAL_ERROR;     
354         }
355         for (i=0; c<c2; c++, i++) {
356                 name[i] = *c;
357         }
358         name[i] = '\0';
359         if (strlen(name) == 0) {
360                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
361                         "open_connection_url: name is not specified in '%s'", url);
362                 return FATAL_ERROR;     
363         }
364         c = c2;
365         if (*c == ':') c++;
366
367         port = 0;
368         rpl_sock = NULL;
369         switch (proto) {
370                 case UNIXD_SOCK:
371                         if (strlen(c) != 0)
372                                 rpl_sock = c;
373                         break;
374                 case UNIXS_SOCK:
375                         break;
376                 default:
377                         port = atol(c);
378                         if (port == 0) {
379                                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
380                                         "open_connection_url: port is not specified in '%s'", url);
381                                 return FATAL_ERROR;     
382                         }
383                         break;
384         }       
385         return binrpc_open_connection(handle, name, port, proto, rpl_sock, NULL);
386 }
387
388 void binrpc_close_connection(struct binrpc_handle* handle)
389 {
390         if (handle->socket != -1) {
391                 close(handle->socket);
392                 handle->socket = -1;
393         }
394         if (handle->buf) {
395                 binrpc_free(handle->buf);
396                 handle->buf = NULL;
397         }
398 }
399
400 /* returns: -1 on error, number of bytes written on success */
401 static int send_binrpc_cmd(struct binrpc_handle* handle, struct binrpc_pkt *pkt, int cookie)
402 {
403         struct iovec v[IOVEC_CNT];
404         unsigned char msg_hdr[BINRPC_MAX_HDR_SIZE];
405         int n;
406         
407         if ((n=binrpc_build_hdr(BINRPC_REQ, binrpc_pkt_len(pkt), cookie, msg_hdr,
408                                                         BINRPC_MAX_HDR_SIZE)) < 0) {
409                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
410                         "send_binrpc_cmd: build header error: %s",
411                         binrpc_error(n));
412                 return FATAL_ERROR;
413         }
414         v[0].iov_base=msg_hdr;
415         v[0].iov_len=n;
416         v[1].iov_base=pkt->body;
417         v[1].iov_len=binrpc_pkt_len(pkt);
418 write_again:
419         if ((n=writev(handle->socket, v, 2))<0){
420                 if (errno==EINTR)
421                         goto write_again;
422                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1, 
423                         "send_binrpc_cmd: send packet failed: %s (%d)", strerror(errno), errno);
424                 return FATAL_ERROR;
425         }
426         return n;
427 }
428
429
430 /* reads the whole reply
431  * returns < 0 on error, reply size on success + initializes resp_handle */
432 static int get_reply(struct binrpc_handle *handle, 
433                         int cookie, 
434                         struct binrpc_response_handle *resp_handle)
435 {
436         unsigned char *crt, *hdr_end;
437         int n, ret, tl;
438         
439         ret = 0;
440         resp_handle->reply_buf = NULL;
441         hdr_end = crt = handle->buf;
442         
443         do {            
444                 n = read(handle->socket, crt, handle->buf_size - (crt-handle->buf));
445                 if (n <= 0){
446                         if (errno==EINTR)
447                                 continue;
448                         if (n == 0)
449                                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
450                                         "get_reply: read unexpected EOF: received %d bytes"
451                                         " of reply", (int)(long)(crt - handle->buf));
452                         else
453                                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
454                                         "get_reply: read reply failed: %s (%d)",
455                                         strerror(errno), errno);
456                         return FATAL_ERROR;
457                 }
458                 if (verbose >= 3){
459                         /* dump it in hex */
460                         printf("received %d bytes in reply (@offset %d):\n", 
461                                n, (int)(crt-handle->buf));
462                         hexdump(crt, n, 1);
463                 }
464                 crt += n;
465                 hdr_end = binrpc_parse_init(&resp_handle->in_pkt, handle->buf, crt - handle->buf, &ret);
466                 
467         } while (ret == E_BINRPC_MORE_DATA);
468         if (ret < 0){
469                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
470                         "get_reply: reply parsing error: %s",
471                         binrpc_error(ret));
472                 return FATAL_ERROR;
473         }
474
475         if (verbose>1){
476                 printf("new packet: type %02x, len %d, cookie %02x\n",
477                                 resp_handle->in_pkt.type, resp_handle->in_pkt.tlen, resp_handle->in_pkt.cookie);
478         }
479         if (resp_handle->in_pkt.cookie!=cookie){
480                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
481                         "get_reply: reply parsing error: "
482                         "cookie doesn't match: sent: %02x, received: %02x", 
483                         cookie, resp_handle->in_pkt.cookie);
484                 return FATAL_ERROR;
485         }
486
487         /* we know total size and we can allocate buffer for received data */
488         tl = resp_handle->in_pkt.tlen;
489         
490         if (handle->sock_type == SOCK_DGRAM) {
491                 /* we must read all datagram in one read call, otherwise unread part is truncated and lost. Read will block execution */
492                 if (crt - hdr_end < tl) {
493                         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
494                                 "get_reply: datagram truncated. Received: %ld, Expected: %d.",
495                                 (long int)(crt-hdr_end), tl);
496                         return FATAL_ERROR;             
497                 }
498         }
499         if (crt - hdr_end > tl) {
500                 /* header contains probably data from next message, in case of STREAM it could be unread but it's waste of time */
501                 crt = hdr_end + tl;     
502         }
503         
504         resp_handle->reply_buf = (unsigned char *) binrpc_malloc(tl);
505         if (!resp_handle->reply_buf) {
506                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
507                         "get_reply: not enough memory to allocate reply buffer. %d bytes needed.",
508                         resp_handle->in_pkt.tlen);
509                 return FATAL_ERROR;
510         }
511         crt = resp_handle->reply_buf + (crt-hdr_end);
512         memcpy(resp_handle->reply_buf, hdr_end, crt - resp_handle->reply_buf);
513         tl -= crt - resp_handle->reply_buf;
514         while (tl > 0) {
515                 n=read(handle->socket, crt, tl);
516                 if (n < 0){
517                         if (errno==EINTR)
518                                 continue;
519                         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
520                                 "get_reply: read reply failed: %s (%d)",
521                                 strerror(errno), errno);
522                         binrpc_free(resp_handle->reply_buf);
523                         resp_handle->reply_buf = NULL;
524                         return FATAL_ERROR;
525                 }
526                 if (verbose >= 3){
527                         /* dump it in hex */
528                         printf("received %d bytes in reply (@offset %d):\n", 
529                                n, (int)(crt-resp_handle->reply_buf));
530                         hexdump(crt, n, 1);
531                 }
532                 crt += n;
533                 tl -= n;
534         }
535         
536         return (int)(crt-resp_handle->reply_buf);
537 }
538
539 int binrpc_send_command_ex(
540         struct binrpc_handle* handle, struct binrpc_pkt *pkt, 
541         struct binrpc_response_handle *resp_handle)
542 {
543         int cookie;
544         
545         cookie = gen_cookie();
546         if (send_binrpc_cmd(handle, pkt, cookie) < 0) {
547                 return FATAL_ERROR;
548         }
549         /* read reply */
550         memset(&resp_handle->in_pkt, 0, sizeof(resp_handle->in_pkt));
551         if (get_reply(handle, cookie, resp_handle) < 0) {
552                 return FATAL_ERROR;
553         }
554         
555         /* normal exit */
556         return 0;
557 }
558
559 static int parse_arg(struct binrpc_val* v, char* arg)
560 {
561         int i=0;
562         double f;
563         char* tmp;
564         int len;
565
566         f = 0.0;
567
568         if (*arg)
569                 i=strtol(arg, &tmp, 10);
570         else
571                 tmp = 0;
572         if ((tmp==0) || (*tmp)){
573                 if (*arg)
574                         f=strtod(arg, &tmp);
575                 if ((tmp==0) || (*tmp)){
576                         /* not an int or a float => string */
577                         len=strlen(arg);
578                         if ((len>=2) && (arg[0]=='s') && (arg[1]==':')){
579                                 tmp=&arg[2];
580                                 len-=2;
581                         }else{
582                                 tmp=arg;
583                         }
584                         v->type=BINRPC_T_STR;
585                         v->u.strval.s=tmp;
586                         v->u.strval.len=len;
587                 }else{ /* float */
588                         v->type=BINRPC_T_DOUBLE;
589                         v->u.fval=f;
590                 }
591         }else{ /* int */
592                 v->type=BINRPC_T_INT;
593                 v->u.intval=i;
594         }
595         return 0;
596 }
597
598
599 /* parse the body into a malloc allocated,  binrpc_val array */
600 int binrpc_send_command(
601         struct binrpc_handle* handle, char* method, char** args, int arg_count,
602         struct binrpc_response_handle *resp_handle)
603 {
604         struct binrpc_pkt req_pkt;
605         struct binrpc_val v;
606         int i, size, res = FATAL_ERROR, ret = 0;
607         unsigned char *req_buf = NULL;
608
609         memset(&resp_handle->in_pkt, 0, sizeof(resp_handle->in_pkt));   
610         if (!method || strlen(method) == 0) {
611                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
612                         "send_command: method name not specified");
613                 goto fail;
614         
615         }
616         size = BINRPC_MIN_RECORD_SIZE + 8 + strlen(method) + 1; /*max.possible optional value len */    
617         for (i=0; i<arg_count; i++) {
618                 if (parse_arg(&v, args[i]) < 0)
619                         goto fail;
620                 switch (v.type) {
621                         case BINRPC_T_STR:
622                                 size += v.u.strval.len + 1;
623                                 break;
624                         case BINRPC_T_INT:
625                         case BINRPC_T_DOUBLE:
626                                 size += sizeof(int);
627                                 break;
628                         default:
629                                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
630                                         "BUG: send_command: unexpected value type");
631                                 goto fail;
632                 }
633                 size +=  BINRPC_MIN_RECORD_SIZE + 8;
634         }
635         req_buf = binrpc_malloc(size);
636         if (!req_buf) {
637                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
638                         "send_command: not enough memory to allocate buffer. Needed %d bytes", size);
639                 goto fail;
640         }
641         if ((ret = binrpc_init_pkt(&req_pkt, req_buf, size)) < 0) goto fail2;
642
643         if ((ret = binrpc_addstr(&req_pkt, method, strlen(method))) < 0) goto fail2;
644
645         for (i=0; i<arg_count; i++) {
646                 if (parse_arg(&v, args[i]) < 0)
647                         goto fail;
648                 switch (v.type) {
649                         case BINRPC_T_STR:
650                                 if ((ret = binrpc_addstr(&req_pkt,  v.u.strval.s,  v.u.strval.len)) < 0) goto fail2;
651                                 break;
652                         case BINRPC_T_INT:
653                                 if ((ret = binrpc_addint(&req_pkt, v.u.intval)) < 0) goto fail2;
654                                 break;
655                         case BINRPC_T_DOUBLE:
656                                 if ((ret = binrpc_adddouble(&req_pkt, v.u.fval)) < 0) goto fail2;
657                                 break;
658                         default:
659                                 break;
660                 }
661         }
662
663         if (binrpc_send_command_ex(handle, &req_pkt, resp_handle) < 0) {
664                 goto fail;
665         }
666         res = 0;
667 fail:   
668         if (req_buf) binrpc_free(req_buf);
669         return res;     
670 fail2:
671         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
672                 "send_command: error when preparing params: %s", binrpc_error(ret));
673         goto fail;
674 }
675
676 void binrpc_release_response(struct binrpc_response_handle *resp_handle) {
677         if (resp_handle->reply_buf) {
678                 binrpc_free(resp_handle->reply_buf);
679                 resp_handle->reply_buf = NULL;
680         }
681 }
682
683 int binrpc_get_response_type(struct binrpc_response_handle *resp_handle)
684 {
685         switch(resp_handle->in_pkt.type) {
686                 case BINRPC_FAULT:
687                         return 1;
688                         break;
689                 case BINRPC_REPL:
690                         return 0;
691                         break;
692                 default:
693                         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
694                                 "BUG: get_response_type: not a reply");
695                         return FATAL_ERROR;
696         }
697 }
698
699 /* parses strings like "bla bla %v 10%% %v\n test=%v",
700  * and stops at each %v,  returning  a pointer after the %v, setting *size
701  * to the string length (not including %v) and *type to the corresponding
702  * BINRPC type (for now only BINRPC_T_ALL).
703  * To escape a '%', use "%%", and check for type==-1 (which means skip an call
704  *  again parse_fmt).
705  * Usage:
706  *        n="test: %v,%v,%v\n";
707  *        while(*n){
708  *          s=n;
709  *          n=parse_fmt(n, &type, &size);
710  *          printf("%.*s", size, s);
711  *          if (type==-1)
712  *            continue;
713  *          else 
714  *             printf("now we should get & print an object of type %d\n", type)
715  *        }
716  */
717 static char* parse_fmt(char* fmt, int* type, int* size)
718 {
719         char* s;
720
721         s=fmt;
722         do{
723                 for(;*fmt && *fmt!='%'; fmt++);
724                 if (*fmt=='%'){
725                         switch(*(fmt+1)){
726                                 case 'v':
727                                         *type=BINRPC_T_ALL;
728                                         *size=(int)(fmt-s);
729                                         return (fmt+2);
730                                         break;
731                                 case '%':
732                                         /* escaped % */
733                                         *size=(int)(fmt-s)+1;
734                                         *type=-1; /* skip */
735                                         return (fmt+2);
736                                         break;
737                         }
738                 }
739         }while(*fmt);
740         *type=-1; /* no value */
741         *size=(fmt-s);
742         return fmt;
743 }
744
745 static void print_binrpc_val(struct binrpc_val* v, int ident)
746 {
747         int r;
748
749         if ((v->type==BINRPC_T_STRUCT) && !v->u.end)
750                 ident--; /* fix to have strut beg. idented differently */
751         for (r=0; r<ident; r++) putchar('       ');
752         if (v->name.s){
753                 printf("%.*s: ", v->name.len, v->name.s);
754         }
755         switch(v->type){
756                 case BINRPC_T_INT:
757                         printf("%d", v->u.intval);
758                         break;
759                 case BINRPC_T_STR:
760                 case BINRPC_T_BYTES:
761                         printf("%.*s", v->u.strval.len, v->u.strval.s);
762                         break;
763                 case BINRPC_T_ARRAY:
764                         printf("%c", (v->u.end)?']':'[');
765                         break;
766                 case BINRPC_T_STRUCT:
767                         printf("%c", (v->u.end)?'}':'{');
768                         break;
769                         default:
770                                 printf("ERROR: unknown type %d\n", v->type);
771         }
772 }
773
774 int binrpc_print_response(struct binrpc_response_handle *resp_handle, char* fmt)
775 {
776         unsigned char* p;
777         unsigned char* end;
778         struct binrpc_val val;
779         int ret;
780         int rec;
781         char *f;
782         char* s;
783         int f_size;
784         int fmt_has_values;
785         
786         if (!resp_handle) {
787                 goto error;
788         }
789         resp_handle->in_pkt.offset = resp_handle->in_pkt.in_struct = resp_handle->in_pkt.in_array = 0;
790
791         p=resp_handle->reply_buf;
792         end=p+resp_handle->in_pkt.tlen;
793         rec=0;
794         f=fmt;
795         fmt_has_values=0;
796         /* read body */
797         while(p<end){
798                 if (f){
799                                         
800                         do{
801                                 if (*f==0)
802                                         f=fmt; /* reset */
803                                 s=f;
804                                 f=parse_fmt(f, &val.type, &f_size);
805                                 printf("%.*s", f_size, s);
806                                 if (val.type!=-1){
807                                         fmt_has_values=1;
808                                         goto read_value;
809                                 }
810                         }while(*f || fmt_has_values);
811                         val.type=BINRPC_T_ALL;
812                 }else{
813                         val.type=BINRPC_T_ALL;
814                 }
815 read_value:
816                 val.name.s=0;
817                 val.name.len=0;
818                 p=binrpc_read_record(&resp_handle->in_pkt, p, end, &val, 0, &ret);
819                 if (ret<0){
820                         if (fmt)
821                                 putchar('\n');
822                         /*if (ret==E_BINRPC_MORE_DATA)
823                                 goto error_read_again;*/
824                         if (ret==E_BINRPC_EOP){
825                                 printf("end of message detected\n");
826                                 break;
827                         }
828                         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
829                                         "error while parsing the record %d,"
830                                         " @%d: %02x : %s", rec,
831                                         resp_handle->in_pkt.offset, *p, binrpc_error(ret));
832                         goto error;
833                 }
834                 rec++;
835                 if (fmt){
836                         print_binrpc_val(&val, 0);
837                 }else{
838                         print_binrpc_val(&val, resp_handle->in_pkt.in_struct+resp_handle->in_pkt.in_array);
839                         putchar('\n');
840                 }
841         }
842         if (fmt && *f){
843                 /* print the rest, with empty values */
844                 while(*f){
845                         s=f;
846                         f=parse_fmt(f, &val.type, &f_size);
847                         printf("%.*s", f_size, s);
848                 }
849         }
850         return 0;
851 error:
852         return FATAL_ERROR;
853 /*error_read_again:
854         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
855                 "ERROR: more data needed");
856         return -2;
857         */
858 }
859
860
861 void binrpc_free_rpc_array(struct binrpc_val* a, int size)
862 {
863         int r;
864         for (r=0; r<size; r++){
865                 if (a[r].name.s)
866                         binrpc_free(a[r].name.s);
867                 if ((a[r].type==BINRPC_T_STR || a[r].type==BINRPC_T_BYTES) &&
868                                 a[r].u.strval.s){
869                         binrpc_free(a[r].u.strval.s);
870                 }
871         }
872         binrpc_free(a);
873 }
874
875
876 #define VAL_ARRAY_CHUNK 100
877 int binrpc_parse_response(struct binrpc_val** vals, int* val_count,
878         struct binrpc_response_handle *resp_handle)
879 {
880         struct binrpc_val val;
881         unsigned char *p, *end;
882         int ret, i;
883
884         resp_handle->in_pkt.offset = resp_handle->in_pkt.in_struct = resp_handle->in_pkt.in_array = 0;
885
886         i=0;
887         if (*val_count==0){
888                 *val_count=VAL_ARRAY_CHUNK; /* start with a reasonable size */
889         }
890         *vals = (struct binrpc_val*) binrpc_malloc(*val_count*sizeof(**vals));
891         if (*vals == 0)
892                 goto error_mem;
893         p = resp_handle->reply_buf;
894         end = p + resp_handle->in_pkt.tlen;
895         
896         /* read body */
897         while(p < end){
898                 val.type = BINRPC_T_ALL;
899                 val.name.s = 0;
900                 val.name.len = 0;
901                 p = binrpc_read_record(&resp_handle->in_pkt, p, end, &val, 0, &ret);
902                 if (ret<0){
903                         if (ret==E_BINRPC_EOP){
904                                 break;
905                         }
906                         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
907                                         "ERROR while parsing the record %d,"
908                                         " @%d: %02x : %s", i,
909                                         resp_handle->in_pkt.offset, *p, binrpc_error(ret));
910                         goto error;
911                 }
912                 if (i >= *val_count){
913                         struct binrpc_val *t;
914                         t= (struct binrpc_val*) binrpc_realloc(*vals, (VAL_ARRAY_CHUNK+(*val_count))*sizeof(**vals));
915                         if (t==0)
916                                 goto error_mem;
917                         *vals = t;
918                         *val_count += VAL_ARRAY_CHUNK;
919                 }
920                 (*vals)[i] = val;
921                 if (val.name.s){
922                         if (((*vals)[i].name.s=binrpc_malloc(val.name.len+1))==0)
923                                 goto error_mem;
924                         memcpy((*vals)[i].name.s, val.name.s, val.name.len);
925                         (*vals)[i].name.s[val.name.len]=0; /* 0-term */
926                 }
927                 if (val.u.strval.s){
928                         if (val.type==BINRPC_T_STR){
929                                 if (((*vals)[i].u.strval.s=
930                                                         binrpc_malloc(val.u.strval.len+1))==0)
931                                         goto error_mem;
932                                 memcpy((*vals)[i].u.strval.s, val.u.strval.s,
933                                                 val.u.strval.len);
934                                 (*vals)[i].u.strval.s[val.u.strval.len]=0; /* 0-term */
935                         }else if (val.type==BINRPC_T_BYTES){
936                                 if (((*vals)[i].u.strval.s=binrpc_malloc(val.u.strval.len))==0)
937                                         goto error_mem;
938                                 memcpy((*vals)[i].u.strval.s, val.u.strval.s, 
939                                                 val.u.strval.len);
940                         }
941                 }
942                 i++;
943         }
944         if (i == 0) {
945                 binrpc_free(*vals);
946                 *vals = NULL;
947         }
948         else if (i<*val_count){
949 /*              do not try to save memory because it causes fragmentation when used ser mem utils and "regualar" memory leak
950                 struct binrpc_val *t;
951                 t = (struct binrpc_val*) binrpc_realloc(*vals, i*sizeof(**vals));
952                 if (t) *vals = t;
953 */
954         }
955         *val_count = i;
956         return 0;
957 error_mem:
958         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
959                 "parse_response: out of memory");
960 error:
961         if (*vals){
962                 binrpc_free_rpc_array(*vals, i);
963                 *vals = NULL;
964         }
965         *val_count=0;
966         return FATAL_ERROR;
967 }
968
969 int binrpc_parse_error_response(
970         struct binrpc_response_handle *resp_handle,
971         int *err_no,
972         char **err) 
973 {
974         struct binrpc_val val;
975         unsigned char *p, *end;
976         int ret;
977
978         resp_handle->in_pkt.offset = resp_handle->in_pkt.in_struct = resp_handle->in_pkt.in_array = 0;
979         p = resp_handle->reply_buf;
980         end = p+resp_handle->in_pkt.tlen;
981         
982         val.type=BINRPC_T_INT;
983         val.name.s=0;
984         val.name.len=0;
985         p = binrpc_read_record(&resp_handle->in_pkt, p, end, &val, 0, &ret);
986         if (ret < 0) {
987                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
988                         "parse_error_response: error when parsing reply (code): %s", binrpc_error(ret)
989                 );
990                 return FATAL_ERROR;
991         }
992         *err_no = val.u.intval;
993
994         val.type=BINRPC_T_STR;
995         p = binrpc_read_record(&resp_handle->in_pkt, p, end, &val, 0, &ret);
996         if (ret < 0) {
997                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
998                         "parse_error_response: error when parsing reply (str): %s", binrpc_error(ret)
999                 );
1000                 return FATAL_ERROR;
1001         }                                                                                                                                                                                                                                                                               
1002         *err = val.u.strval.s;  /* it's null terminated */
1003         return 0;
1004 }
1005
1006 /* returns a pointer to a static buffer containing l in asciiz & sets len */
1007 static inline char* int2str_internal(unsigned int l, int* len)
1008 {
1009         static char r[INT2STR_MAX_LEN];
1010         int i;
1011         
1012         i=INT2STR_MAX_LEN-2;
1013         r[INT2STR_MAX_LEN-1]=0; /* null terminate */
1014         do{
1015                 r[i]=l%10+'0';
1016                 i--;
1017                 l/=10;
1018         }while(l && (i>=0));
1019         if (l && (i<0)){
1020                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
1021                         "BUG: int2str_internal: overflow");
1022         }
1023         if (len) *len=(INT2STR_MAX_LEN-2)-i;
1024         return &r[i+1];
1025 }
1026
1027 static int realloc_buf(unsigned char** buf, int* buf_len, int req_len)
1028
1029         unsigned char*  tmp_buf;
1030         int orig_len;
1031         
1032         orig_len = (*buf == NULL) ? 0 : strlen((char *) *buf);
1033         *buf_len += (TEXT_BUFF_ALLOC_CHUNK < req_len) ? TEXT_BUFF_ALLOC_CHUNK + req_len : TEXT_BUFF_ALLOC_CHUNK;
1034         
1035         if (*buf == NULL)
1036                 tmp_buf = (unsigned char *) binrpc_malloc(orig_len + *buf_len);
1037         else
1038                 tmp_buf = (unsigned char *) binrpc_realloc(*buf, orig_len + *buf_len);
1039         if (tmp_buf == 0) {
1040                 snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
1041                         "ERROR: out of memory");
1042                 return FATAL_ERROR;
1043         }
1044         
1045         *buf = tmp_buf;
1046         (*buf)[orig_len] = '\0';
1047
1048         return 0;
1049 }
1050
1051 static inline int str2buffer(unsigned char** buf, int* buf_len, int* pos, 
1052                              char* data, int data_len)
1053 {
1054         if (*buf_len < data_len) {
1055                 if(realloc_buf(buf, buf_len, data_len) != 0) {
1056                         return FATAL_ERROR;
1057                 }
1058         }
1059         
1060         memcpy(&(*buf)[*pos], data, data_len);
1061         *pos += data_len;
1062         *buf_len -= data_len;
1063         
1064         return 0;
1065 }
1066
1067 static inline int char2buffer(unsigned char** buf, int* buf_len, int* pos, 
1068                               char data)
1069 {
1070         if (*buf_len < 1) {
1071                 if(realloc_buf(buf, buf_len, 1) != 0) {
1072                         return FATAL_ERROR;
1073                 }
1074         }
1075         
1076         (*buf)[*pos] = data;
1077         ++(*pos);
1078         --(*buf_len);
1079         
1080         return 0;
1081 }
1082
1083 static int val2buffer(struct binrpc_val* v, unsigned char** buf, 
1084                              int *buf_len, int* pos)
1085 {
1086         char *number;
1087         int num_len; 
1088          
1089         if (v->name.s){
1090                 if(str2buffer(buf, buf_len, pos, v->name.s, v->name.len) != 0) {
1091                         return FATAL_ERROR;
1092                 }
1093                 if(str2buffer(buf, buf_len, pos, ": ", strlen(": ")) != 0) {  /* TODO: common format */
1094                         return FATAL_ERROR;
1095                 }
1096                 
1097         }
1098         
1099         switch(v->type){
1100                 case BINRPC_T_INT:
1101                         num_len = 0;
1102                         number = NULL;
1103                         number = int2str_internal(v->u.intval, &num_len);
1104                         if (number == NULL) {
1105                                 printf("ERROR: Conversion of %d into string failed.\n", v->type);
1106                                 return FATAL_ERROR;
1107                         }
1108                         
1109                         if(str2buffer(buf, buf_len, pos, number, num_len) != 0) {
1110                                 return FATAL_ERROR;
1111                         }
1112                         break;
1113                 case BINRPC_T_STR:
1114                 case BINRPC_T_BYTES:
1115                         if(str2buffer(buf, buf_len, pos, v->u.strval.s, v->u.strval.len) != 0) {
1116                                 return FATAL_ERROR;
1117                         }
1118                         break;
1119                 case BINRPC_T_ARRAY:
1120                         if(char2buffer(buf, buf_len, pos, (v->u.end) ? ']' : '[') != 0) {
1121                                 return FATAL_ERROR;
1122                         }
1123                         break;
1124                 case BINRPC_T_STRUCT:
1125                         if(char2buffer(buf, buf_len, pos, (v->u.end) ? '}' : '{') != 0) {
1126                                 return FATAL_ERROR;
1127                         }
1128                         break;
1129                 default:
1130                         printf("ERROR: unknown type %d\n", v->type);
1131                         return FATAL_ERROR;
1132         };
1133         
1134         return 0;
1135 }
1136
1137 int binrpc_response_to_text(
1138         struct binrpc_response_handle *resp_handle,
1139         unsigned char** txt_rsp, int* txt_rsp_len, char delimiter)
1140 {
1141         unsigned char* p;
1142         unsigned char* end;
1143         struct binrpc_val val;
1144         int ret;
1145         int rec;
1146         int pos;
1147         
1148         pos = 0;
1149         
1150         if (!resp_handle) {
1151                 goto error;
1152         }
1153
1154         memset(&val, 0, sizeof(struct binrpc_val));
1155         resp_handle->in_pkt.offset = resp_handle->in_pkt.in_struct = resp_handle->in_pkt.in_array = 0;
1156         
1157         p=resp_handle->reply_buf;
1158         end=p+resp_handle->in_pkt.tlen;
1159         rec=0;
1160         
1161         if (*txt_rsp == NULL) {
1162                 *txt_rsp_len = 0;
1163                 if (realloc_buf(txt_rsp, txt_rsp_len, 0) != 0) {
1164                         goto error;
1165                 } 
1166         }
1167         
1168         /* read body */
1169         while(p<end){
1170                 val.type=BINRPC_T_ALL;
1171                 val.name.s=0;
1172                 val.name.len=0;
1173                 p = binrpc_read_record(&resp_handle->in_pkt, p, end, &val, 0, &ret);
1174                 if (ret < 0) {
1175                         if (ret == E_BINRPC_EOP) {
1176                                 printf("end of message detected\n");
1177                                 break;
1178                         }
1179                         snprintf(binrpc_last_errs, sizeof(binrpc_last_errs)-1,
1180                                         "ERROR while parsing the record %d,"
1181                                         " @%d: %02x : %s", rec, resp_handle->in_pkt.offset, *p, binrpc_error(ret));
1182                         goto error;
1183                 }
1184                 rec++;
1185                 if (val2buffer(&val, txt_rsp, txt_rsp_len, &pos) != 0) {
1186                         goto error;
1187                 }
1188                 
1189                 if(char2buffer(txt_rsp, txt_rsp_len, &pos, delimiter) != 0) {
1190                         goto error;
1191                 }
1192         }
1193         
1194         /* rewrite last char - we don't need delimiter there */
1195         (*txt_rsp)[pos-1] = '\0';   
1196         /*
1197         if(char2buffer(txt_rsp, txt_rsp_len, &pos, '\0') != 0) {
1198                 goto error;
1199         }
1200         */
1201         return 0;
1202 error:
1203         return FATAL_ERROR;
1204 }
1205
1206 int main(int argc, char** argv)
1207 {
1208         struct binrpc_response_handle resp_handle;
1209         unsigned char* txt_rsp = NULL;
1210         int txt_rsp_len = 0;
1211         struct binrpc_handle handle;
1212         struct binrpc_val *vals = NULL;
1213         int cnt, i, err_no;
1214         char *errs;
1215         
1216         if (argc < 2) goto err;
1217         
1218         if (binrpc_open_connection_url(&handle, argv[1]) < 0) goto err2;
1219         if (binrpc_send_command(&handle, argv[2], argv+3, argc-3, &resp_handle) < 0) {
1220                 binrpc_close_connection(&handle);
1221                 goto err2;
1222         }
1223         binrpc_close_connection(&handle);
1224
1225         if (binrpc_response_to_text(&resp_handle, &txt_rsp, &txt_rsp_len, '\n') < 0) goto err3;
1226         fprintf(stdout, "binrpc_response_to_text():\n--------------------------\n%s\n", txt_rsp);
1227         
1228         fprintf(stdout, "\nbinrpc_print_response():\n------------------------\n");
1229         binrpc_print_response(&resp_handle, NULL);
1230         
1231         fprintf(stdout, "\nbinrpc_parse_response():\n------------------------\n");
1232         cnt = 0;
1233         switch (binrpc_get_response_type(&resp_handle)) {
1234                 case 0:
1235                         if (binrpc_parse_response(&vals, &cnt, &resp_handle) < 0) goto err3;
1236                         fprintf(stdout, "#Records: %d\n", cnt);
1237                         for (i = 0; i < cnt; i++) {
1238                                 fprintf(stdout, "#%.2d: type:%d name:%.*s\n", i, vals[i].type, vals[i].name.len, vals[i].name.s);
1239                         }
1240                         break;
1241                 case 1:
1242                         if (binrpc_parse_error_response(&resp_handle, &err_no, &errs) <0) goto err3;
1243                         fprintf(stdout, "%d %s\n", err_no, errs);
1244                         break;
1245                 default:
1246                         fprintf(stdout, "Unknown response type: %d\n", binrpc_get_response_type(&resp_handle)); 
1247                         break;
1248         }
1249
1250         if (vals != NULL) {
1251                 binrpc_free_rpc_array(vals, cnt);
1252         }       
1253         if (txt_rsp != NULL) {
1254                 binrpc_free(txt_rsp);
1255         }
1256         binrpc_release_response(&resp_handle);
1257         
1258         return 0;
1259 err:
1260         fprintf(stderr, "Usage: %s url mathod [params]\n", NAME);
1261         return -1;
1262 err3:
1263         if (vals != NULL) {
1264                 binrpc_free_rpc_array(vals, cnt);
1265         }       
1266         if (txt_rsp) {
1267                 binrpc_free(txt_rsp);
1268         }
1269         binrpc_release_response(&resp_handle);
1270 err2:
1271         fprintf(stderr, "ERROR: %s\n", binrpc_get_last_errs());
1272         return -2;
1273 }
1274