Bug fixes, mostly.
[yaz-moved-to-github.git] / odr / ber_any.c
1 /*
2  * Copyright (C) 1994, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: ber_any.c,v $
7  * Revision 1.2  1995-02-10 15:55:28  quinn
8  * Bug fixes, mostly.
9  *
10  * Revision 1.1  1995/02/09  15:51:45  quinn
11  * Works better now.
12  *
13  */
14
15 #include <odr.h>
16
17 int ber_any(ODR o, Odr_any **p)
18 {
19     int res;
20
21     switch (o->direction)
22     {
23         case ODR_DECODE:
24             if ((res = completeBER(o->bp, 1000)) <= 0)        /* FIX THIS */
25                 return 0;
26             (*p)->buf = nalloc(o, res);
27             memcpy((*p)->buf, o->bp, res);
28             (*p)->len = (*p)->size = res;
29             o->bp += res;
30             o->left -= res;
31             return 1;
32         case ODR_ENCODE:
33             if ((*p)->len > o->left)
34                 return 0;
35             memcpy(o->bp , (*p)->buf, (*p)->len);
36             o->bp += (*p)->len;
37             o->left -= (*p)->len;
38             return 1;
39         default: return 0;
40     }
41 }
42
43 /*
44  * Return length of BER-package or -1.
45  */
46 int completeBER(unsigned char *buf, int len)
47 {
48     int res, ll, class, tag, cons;
49     unsigned char *b = buf;
50     
51     if (!buf[0] && !buf[1])
52         return -1;
53     if ((res = ber_dectag(b, &class, &tag, &cons)) <= 0)
54         return 0;
55     if (res > len)
56         return -1;
57     b += res;
58     len -= res;
59     if ((res = ber_declen(b, &ll)) <= 0)
60         return -1;
61     if (res > len)
62         return -1;
63     b += res;
64     len -= res;
65     if (ll >= 0)
66         return (len >= ll ? ll + (b-buf) : -1);
67     if (!cons)
68         return -1;    
69     while (1)
70     {
71         if ((res = completeBER(b, len)) < 0)
72             return -1;
73         b += res;
74         len -= res;
75         if (len < 2)
76             return -1;
77         if (*b == 0 && *(b + 1) == 0)
78             return (b - buf) + 2;
79     }
80 }