Adjustments.
[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.4  1995-02-14 11:54:33  quinn
8  * Adjustments.
9  *
10  * Revision 1.3  1995/02/10  18:57:24  quinn
11  * More in the way of error-checking.
12  *
13  * Revision 1.2  1995/02/10  15:55:28  quinn
14  * Bug fixes, mostly.
15  *
16  * Revision 1.1  1995/02/09  15:51:45  quinn
17  * Works better now.
18  *
19  */
20
21 #include <odr.h>
22
23 int ber_any(ODR o, Odr_any **p)
24 {
25     int res;
26
27     switch (o->direction)
28     {
29         case ODR_DECODE:
30             if ((res = completeBER(o->bp, 1000)) <= 0)        /* FIX THIS */
31                 return 0;
32             (*p)->buf = nalloc(o, res);
33             memcpy((*p)->buf, o->bp, res);
34             (*p)->len = (*p)->size = res;
35             o->bp += res;
36             o->left -= res;
37             return 1;
38         case ODR_ENCODE:
39             if ((*p)->len > o->left)
40                 return 0;
41             memcpy(o->bp , (*p)->buf, (*p)->len);
42             o->bp += (*p)->len;
43             o->left -= (*p)->len;
44             return 1;
45         default: return 0;
46     }
47 }
48
49 /*
50  * Return length of BER-package or 0.
51  */
52 int completeBER(unsigned char *buf, int len)
53 {
54     int res, ll, class, tag, cons;
55     unsigned char *b = buf;
56     
57     if (!buf[0] && !buf[1])
58         return 0;
59     if ((res = ber_dectag(b, &class, &tag, &cons)) <= 0)
60         return 0;
61     if (res > len)
62         return 0;
63     b += res;
64     len -= res;
65     if ((res = ber_declen(b, &ll)) <= 0)
66         return 0;
67     if (res > len)
68         return 0;
69     b += res;
70     len -= res;
71     if (ll >= 0)
72         return (len >= ll ? ll + (b-buf) : 0);
73     if (!cons)
74         return 0;    
75     while (1)
76     {
77         if (!(res = completeBER(b, len)))
78             return 0;
79         b += res;
80         len -= res;
81         if (len < 2)
82             return 0;
83         if (*b == 0 && *(b + 1) == 0)
84             return (b - buf) + 2;
85     }
86 }