License, documentation, and memory fixes
[yaz-moved-to-github.git] / odr / ber_oct.c
1 /*
2  * Copyright (c) 1995, Index Data
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: ber_oct.c,v $
7  * Revision 1.8  1995-05-16 08:50:47  quinn
8  * License, documentation, and memory fixes
9  *
10  * Revision 1.7  1995/04/18  08:15:17  quinn
11  * Added dynamic memory allocation on encoding (whew). Code is now somewhat
12  * neater. We'll make the same change for decoding one day.
13  *
14  * Revision 1.6  1995/03/17  10:17:41  quinn
15  * Added memory management.
16  *
17  * Revision 1.5  1995/03/08  12:12:10  quinn
18  * Added better error checking.
19  *
20  * Revision 1.4  1995/02/10  15:55:28  quinn
21  * Bug fixes, mostly.
22  *
23  * Revision 1.3  1995/02/03  17:04:34  quinn
24  * *** empty log message ***
25  *
26  * Revision 1.2  1995/02/02  20:38:50  quinn
27  * Updates.
28  *
29  * Revision 1.1  1995/02/02  16:21:52  quinn
30  * First kick.
31  *
32  */
33
34 #include <odr.h>
35
36 int ber_octetstring(ODR o, Odr_oct *p, int cons)
37 {
38     int res, len;
39     unsigned char *base, *c;
40
41     switch (o->direction)
42     {
43         case ODR_DECODE:
44             if ((res = ber_declen(o->bp, &len)) < 0)
45             {
46                 o->error = OPROTO;
47                 return 0;
48             }
49             o->bp += res;
50             o->left -= res;
51             if (cons)       /* fetch component strings */
52             {
53                 base = o->bp;
54                 while (odp_more_chunks(o, base, len))
55                     if (!odr_octetstring(o, &p, 0))
56                         return 0;
57                 return 1;
58             }
59             /* primitive octetstring */
60             if (len < 0)
61             {
62                 o->error = OOTHER;
63                 return 0;
64             }
65             if (len + 1 > p->size - p->len)
66             {
67                 c = odr_malloc(o, p->size += len + 1);
68                 if (p->len)
69                     memcpy(c, p->buf, p->len);
70                 p->buf = c;
71             }
72             if (len)
73                 memcpy(p->buf + p->len, o->bp, len);
74             p->len += len;
75             o->bp += len;
76             o->left -= len;
77             return 1;
78         case ODR_ENCODE:
79             if ((res = ber_enclen(o, p->len, 5, 0)) < 0)
80                 return 0;
81             if (p->len == 0)
82                 return 1;
83             if (odr_write(o, p->buf, p->len) < 0)
84                 return 0;
85             return 1;
86         case ODR_PRINT: return 1;
87         default: o->error = OOTHER; return 0;
88     }
89 }