Add Zthes tag-set -- where was it?!
[yaz-moved-to-github.git] / odr / ber_oid.c
1 /*
2  * Copyright (c) 1995-2002, Index Data
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Id: ber_oid.c,v 1.13 2002-07-25 12:51:08 adam Exp $
7  */
8 #if HAVE_CONFIG_H
9 #include <config.h>
10 #endif
11
12 #include "odr-priv.h"
13
14 int ber_oidc(ODR o, Odr_oid *p)
15 {
16     int len, lenp, end;
17     int pos, n, res, id;
18     unsigned char octs[8];
19
20     switch (o->direction)
21     {
22     case ODR_DECODE:
23         if ((res = ber_declen(o->bp, &len)) < 1)
24         {
25             o->error = OPROTO;
26             return 0;
27         }
28         if (len < 0)
29         {
30             o->error = OPROTO;
31             return 0;
32         }
33         o->bp += res;
34         if (len == 0)
35         {
36             *p = -1;
37             return 1;
38         }
39         p[0] = *o->bp / 40;
40         if (p[0] > 2)
41             p[0] = 2;
42         p[1] = *o->bp - p[0] * 40;
43         o->bp++;
44         pos = 2;
45         len--;
46         while (len)
47         {
48             p[pos] = 0;
49             do
50             {
51                 if (!len)
52                 {
53                     o->error = OPROTO;
54                     return 0;
55                 }
56                 p[pos] <<= 7;
57                 p[pos] |= *o->bp & 0X7F;
58                 len--;
59             }
60             while (*(o->bp++) & 0X80);
61             pos++;
62         }
63         p[pos] = -1;
64         return 1;
65     case ODR_ENCODE:
66         /* we'll allow ourselves the quiet luxury of only doing encodings
67            shorter than 127 */
68         lenp = odr_tell(o);
69         if (odr_putc(o, 0) < 0)   /* dummy */
70             return 0;
71         if (p[0] < 0 && p[1] <= 0)
72         {
73             o->error = ODATA;
74             return 0;
75         }
76         for (pos = 1; p[pos] >= 0; pos++)
77         {
78             id = pos > 1 ? p[pos] : p[0] * 40 + p[1];
79             n = 0;
80             do
81             {
82                 octs[n++] = id & 0X7F;
83                 id >>= 7;
84             }
85             while (id);
86             while (n--)
87             {
88                 unsigned char p;
89
90                 p = octs[n] | ((n > 0) << 7);
91                 if (odr_putc(o, p) < 0)
92                     return 0;
93             }
94         }
95         end = odr_tell(o);
96         odr_seek(o, ODR_S_SET, lenp);
97         if (ber_enclen(o, (end - lenp) - 1, 1, 1) != 1)
98         {
99             o->error = OOTHER;
100             return 0;
101         }
102         odr_seek(o, ODR_S_END, 0);
103         return 1;
104     default: 
105         o->error = OOTHER; return 0;
106     }
107 }