Bump year
[yaz-moved-to-github.git] / src / ber_oct.c
1 /*
2  * Copyright (C) 1995-2005, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: ber_oct.c,v 1.3 2005-01-15 19:47:11 adam Exp $
6  */
7
8 /** 
9  * \file ber_oct.c
10  * \brief Implements ber_octetstring
11  *
12  * This source file implements BER encoding and decoding of
13  * the OCTETSTRING type.
14  */
15
16 #if HAVE_CONFIG_H
17 #include <config.h>
18 #endif
19
20 #include "odr-priv.h"
21
22 int ber_octetstring(ODR o, Odr_oct *p, int cons)
23 {
24     int res, len;
25     const unsigned char *base;
26     unsigned char *c;
27
28     switch (o->direction)
29     {
30     case ODR_DECODE:
31         if ((res = ber_declen(o->bp, &len, odr_max(o))) < 0)
32         {
33             odr_seterror(o, OPROTO, 14);
34             return 0;
35         }
36         o->bp += res;
37         if (cons)       /* fetch component strings */
38         {
39             base = o->bp;
40             while (odp_more_chunks(o, base, len))
41                 if (!odr_octetstring(o, &p, 0, 0))
42                     return 0;
43             return 1;
44         }
45         /* primitive octetstring */
46         if (len < 0)
47         {
48             odr_seterror(o, OOTHER, 15);
49             return 0;
50         }
51         if (len > odr_max(o))
52         {
53             odr_seterror(o, OOTHER, 16);
54             return 0;
55         }
56         if (len + 1 > p->size - p->len)
57         {
58             c = (unsigned char *)odr_malloc(o, p->size += len + 1);
59             if (p->len)
60                 memcpy(c, p->buf, p->len);
61             p->buf = c;
62         }
63         if (len)
64             memcpy(p->buf + p->len, o->bp, len);
65         p->len += len;
66         o->bp += len;
67         /* the final null is really not part of the buffer, but */
68         /* it helps somes applications that assumes C strings */
69         if (len)
70             p->buf[p->len] = '\0';
71         return 1;
72     case ODR_ENCODE:
73         if ((res = ber_enclen(o, p->len, 5, 0)) < 0)
74             return 0;
75         if (p->len == 0)
76             return 1;
77         if (odr_write(o, p->buf, p->len) < 0)
78             return 0;
79         return 1;
80     case ODR_PRINT:
81         return 1;
82     default:
83         odr_seterror(o, OOTHER, 17);
84         return 0;
85     }
86 }