6c6b1d9e90af34e7dfa89f492d1c857995436529
[apps/agl-service-can-low-level.git] / pb_decode.c
1 /* pb_decode.c -- decode a protobuf using minimal resources
2  *
3  * 2011 Petteri Aimonen <jpa@kapsi.fi>
4  */
5
6
7 #ifdef __GNUC__
8 /* Verify that we remember to check all return values for proper error propagation */
9 #define checkreturn __attribute__((warn_unused_result))
10 #else
11 #define checkreturn
12 #endif
13
14 #include "pb.h"
15 #include "pb_decode.h"
16 #include <string.h>
17
18 typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn;
19
20 /* --- Function pointers to field decoders ---
21  * Order in the array must match pb_action_t LTYPE numbering.
22  */
23 static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = {
24     &pb_dec_varint,
25     &pb_dec_svarint,
26     &pb_dec_fixed,
27     
28     &pb_dec_bytes,
29     &pb_dec_string,
30     &pb_dec_submessage
31 };
32
33 /**************
34  * pb_istream *
35  **************/
36
37 bool checkreturn pb_read(pb_istream_t *stream, uint8_t *buf, size_t count)
38 {
39     if (stream->bytes_left < count)
40         return false;
41     
42     if (!stream->callback(stream, buf, count))
43         return false;
44     
45     stream->bytes_left -= count;
46     return true;
47 }
48
49 static bool checkreturn buf_read(pb_istream_t *stream, uint8_t *buf, size_t count)
50 {
51     uint8_t *source = (uint8_t*)stream->state;
52     
53     if (buf != NULL)
54         memcpy(buf, source, count);
55     
56     stream->state = source + count;
57     return true;
58 }
59
60 pb_istream_t pb_istream_from_buffer(uint8_t *buf, size_t bufsize)
61 {
62     pb_istream_t stream;
63     stream.callback = &buf_read;
64     stream.state = buf;
65     stream.bytes_left = bufsize;
66     return stream;
67 }
68
69 /********************
70  * Helper functions *
71  ********************/
72
73 static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)
74 {
75     uint64_t temp;
76     bool status = pb_decode_varint(stream, &temp);
77     *dest = temp;
78     return status;
79 }
80
81 bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
82 {
83     uint8_t byte;
84     uint8_t bitpos = 0;
85     *dest = 0;
86     
87     while (bitpos < 64 && pb_read(stream, &byte, 1))
88     {
89         *dest |= (uint64_t)(byte & 0x7F) << bitpos;
90         bitpos += 7;
91         
92         if (!(byte & 0x80))
93             return true;
94     }
95     
96     return false;
97 }
98
99 bool checkreturn pb_skip_varint(pb_istream_t *stream)
100 {
101     uint8_t byte;
102     do
103     {
104         if (!pb_read(stream, &byte, 1))
105             return false;
106     } while (byte & 0x80);
107     return true;
108 }
109
110 bool checkreturn pb_skip_string(pb_istream_t *stream)
111 {
112     uint32_t length;
113     if (!pb_decode_varint32(stream, &length))
114         return false;
115     
116     return pb_read(stream, NULL, length);
117 }
118
119 /* Currently the wire type related stuff is kept hidden from
120  * callbacks. They shouldn't need it. It's better for performance
121  * to just assume the correct type and fail safely on corrupt message.
122  */
123
124 static bool checkreturn skip(pb_istream_t *stream, int wire_type)
125 {
126     switch (wire_type)
127     {
128         case PB_WT_VARINT: return pb_skip_varint(stream);
129         case PB_WT_64BIT: return pb_read(stream, NULL, 8);
130         case PB_WT_STRING: return pb_skip_string(stream);
131         case PB_WT_32BIT: return pb_read(stream, NULL, 4);
132         default: return false;
133     }
134 }
135
136 /* Read a raw value to buffer, for the purpose of passing it to callback as
137  * a substream. Size is maximum size on call, and actual size on return.
138  */
139 static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, uint8_t *buf, size_t *size)
140 {
141     size_t max_size = *size;
142     switch (wire_type)
143     {
144         case PB_WT_VARINT:
145             *size = 0;
146             do
147             {
148                 (*size)++;
149                 if (*size > max_size) return false;
150                 if (!pb_read(stream, buf, 1)) return false;
151             } while (*buf++ & 0x80);
152             return true;
153             
154         case PB_WT_64BIT:
155             *size = 8;
156             return pb_read(stream, buf, 8);
157         
158         case PB_WT_32BIT:
159             *size = 4;
160             return pb_read(stream, buf, 4);
161         
162         default: return false;
163     }
164 }
165
166 /* Decode string length from stream and return a substream with limited length */
167 static bool checkreturn make_string_substream(pb_istream_t *stream, pb_istream_t *substream)
168 {
169     uint32_t size;
170     if (!pb_decode_varint32(stream, &size))
171         return false;
172     
173     *substream = *stream;
174     if (substream->bytes_left < size)
175         return false;
176     
177     substream->bytes_left = size;
178     stream->bytes_left -= size;
179     return true;
180 }
181
182 /* Iterator for pb_field_t list */
183 typedef struct {
184     const pb_field_t *start;
185     const pb_field_t *current;
186     int field_index;
187     void *dest_struct;
188     void *pData;
189     void *pSize;
190 } pb_field_iterator_t;
191
192 static void pb_field_init(pb_field_iterator_t *iter, const pb_field_t *fields, void *dest_struct)
193 {
194     iter->start = iter->current = fields;
195     iter->field_index = 0;
196     iter->pData = dest_struct + iter->current->data_offset;
197     iter->pSize = (char*)iter->pData + iter->current->size_offset;
198     iter->dest_struct = dest_struct;
199 }
200
201 static bool pb_field_next(pb_field_iterator_t *iter)
202 {
203     bool notwrapped = true;
204     size_t prev_size = iter->current->data_size;
205     
206     if (PB_HTYPE(iter->current->type) == PB_HTYPE_ARRAY)
207         prev_size *= iter->current->array_size;
208     
209     iter->current++;
210     iter->field_index++;
211     if (iter->current->tag == 0)
212     {
213         iter->current = iter->start;
214         iter->field_index = 0;
215         iter->pData = iter->dest_struct;
216         prev_size = 0;
217         notwrapped = false;
218     }
219     
220     iter->pData = (char*)iter->pData + prev_size + iter->current->data_offset;
221     iter->pSize = (char*)iter->pData + iter->current->size_offset;
222     return notwrapped;
223 }
224
225 static bool checkreturn pb_field_find(pb_field_iterator_t *iter, int tag)
226 {
227     int start = iter->field_index;
228     
229     do {
230         if (iter->current->tag == tag)
231             return true;
232         pb_field_next(iter);
233     } while (iter->field_index != start);
234     
235     return false;
236 }
237
238 /*************************
239  * Decode a single field *
240  *************************/
241
242 static bool checkreturn decode_field(pb_istream_t *stream, int wire_type, pb_field_iterator_t *iter)
243 {
244     pb_decoder_t func = PB_DECODERS[PB_LTYPE(iter->current->type)];
245     
246     switch (PB_HTYPE(iter->current->type))
247     {
248         case PB_HTYPE_REQUIRED:
249             return func(stream, iter->current, iter->pData);
250             
251         case PB_HTYPE_OPTIONAL:
252             *(bool*)iter->pSize = true;
253             return func(stream, iter->current, iter->pData);
254     
255         case PB_HTYPE_ARRAY:
256             if (wire_type == PB_WT_STRING
257                 && PB_LTYPE(iter->current->type) <= PB_LTYPE_LAST_PACKABLE)
258             {
259                 /* Packed array */
260                 size_t *size = (size_t*)iter->pSize;
261                 pb_istream_t substream;
262                 if (!make_string_substream(stream, &substream))
263                     return false;
264                 
265                 while (substream.bytes_left && *size < iter->current->array_size)
266                 {
267                     void *pItem = (uint8_t*)iter->pData + iter->current->data_size * (*size);
268                     if (!func(&substream, iter->current, pItem))
269                         return false;
270                     (*size)++;
271                 }
272                 return (substream.bytes_left == 0);
273             }
274             else
275             {
276                 /* Repeated field */
277                 size_t *size = (size_t*)iter->pSize;
278                 void *pItem = (uint8_t*)iter->pData + iter->current->data_size * (*size);
279                 if (*size >= iter->current->array_size)
280                     return false;
281                 
282                 (*size)++;
283                 return func(stream, iter->current, pItem);
284             }
285         
286         case PB_HTYPE_CALLBACK:
287         {
288             pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
289             
290             if (pCallback->funcs.decode == NULL)
291                 return skip(stream, wire_type);
292             
293             if (wire_type == PB_WT_STRING)
294             {
295                 pb_istream_t substream;
296                 
297                 if (!make_string_substream(stream, &substream))
298                     return false;
299                 
300                 while (substream.bytes_left)
301                 {
302                     if (!pCallback->funcs.decode(&substream, iter->current, pCallback->arg))
303                         return false;
304                 }
305                 return true;
306             }
307             else
308             {
309                 /* Copy the single scalar value to stack.
310                  * This is required so that we can limit the stream length,
311                  * which in turn allows to use same callback for packed and
312                  * not-packed fields. */
313                 pb_istream_t substream;
314                 uint8_t buffer[10];
315                 size_t size = sizeof(buffer);
316                 
317                 if (!read_raw_value(stream, wire_type, buffer, &size))
318                     return false;
319                 substream = pb_istream_from_buffer(buffer, size);
320                 
321                 return pCallback->funcs.decode(&substream, iter->current, pCallback->arg);
322             }
323         }
324         
325         default:
326             return false;
327     }
328 }
329
330 /*********************
331  * Decode all fields *
332  *********************/
333
334 bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
335 {
336     uint32_t fields_seen = 0; /* Used to check for required fields */
337     pb_field_iterator_t iter;
338     int i;
339     
340     pb_field_init(&iter, fields, dest_struct);
341     
342     /* Initialize size/has fields and apply default values */
343     do
344     {
345         if (iter.current->tag == 0)
346             continue;
347         
348         if (PB_HTYPE(iter.current->type) == PB_HTYPE_OPTIONAL)
349         {
350             *(bool*)iter.pSize = false;
351             
352             /* Initialize to default value */
353             if (iter.current->ptr != NULL)
354                 memcpy(iter.pData, iter.current->ptr, iter.current->data_size);
355             else
356                 memset(iter.pData, 0, iter.current->data_size);
357         }
358         else if (PB_HTYPE(iter.current->type) == PB_HTYPE_ARRAY)
359         {
360             *(size_t*)iter.pSize = 0;
361         }
362         else if (PB_HTYPE(iter.current->type) == PB_HTYPE_REQUIRED)
363         {
364             memset(iter.pData, 0, iter.current->data_size);
365         }
366     } while (pb_field_next(&iter));
367     
368     while (stream->bytes_left)
369     {
370         uint32_t temp;
371         int tag, wire_type;
372         if (!pb_decode_varint32(stream, &temp))
373         {
374             if (stream->bytes_left == 0)
375                 break; /* It was EOF */
376             else
377                 return false; /* It was error */
378         }
379         
380         if (temp == 0)
381             break; /* Special feature: allow 0-terminated messages. */
382         
383         tag = temp >> 3;
384         wire_type = temp & 7;
385         
386         if (!pb_field_find(&iter, tag))
387         {
388             /* No match found, skip data */
389             if (!skip(stream, wire_type))
390                 return false;
391             continue;
392         }
393         
394         fields_seen |= 1 << (iter.field_index & 31);
395             
396         if (!decode_field(stream, wire_type, &iter))
397             return false;
398     }
399     
400     /* Check that all required fields (mod 31) were present. */
401     for (i = 0; fields[i].tag != 0; i++)
402     {
403         if (PB_HTYPE(fields[i].type) == PB_HTYPE_REQUIRED &&
404             !(fields_seen & (1 << (i & 31))))
405         {
406             return false;
407         }
408     }
409     
410     return true;
411 }
412
413 /* Field decoders */
414
415 /* Copy destsize bytes from src so that values are casted properly.
416  * On little endian machine, copy first n bytes of src
417  * On big endian machine, copy last n bytes of src
418  * srcsize must always be larger than destsize
419  */
420 static void endian_copy(void *dest, void *src, size_t destsize, size_t srcsize)
421 {
422 #ifdef __BIG_ENDIAN__
423     memcpy(dest, (char*)src + (srcsize - destsize), destsize);
424 #else
425     memcpy(dest, src, destsize);
426 #endif
427 }
428
429 bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
430 {
431     uint64_t temp;
432     bool status = pb_decode_varint(stream, &temp);
433     endian_copy(dest, &temp, field->data_size, sizeof(temp));
434     return status;
435 }
436
437 bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
438 {
439     uint64_t temp;
440     bool status = pb_decode_varint(stream, &temp);
441     temp = (temp >> 1) ^ -(int64_t)(temp & 1);
442     endian_copy(dest, &temp, field->data_size, sizeof(temp));
443     return status;
444 }
445
446 bool checkreturn pb_dec_fixed(pb_istream_t *stream, const pb_field_t *field, void *dest)
447 {
448 #ifdef __BIG_ENDIAN__
449     uint8_t bytes[8] = {0};
450     bool status = pb_read(stream, bytes, field->data_size);
451     uint8_t bebytes[8] = {bytes[7], bytes[6], bytes[5], bytes[4], 
452                           bytes[3], bytes[2], bytes[1], bytes[0]};
453     endian_copy(dest, lebytes, field->data_size, 8);
454     return status;
455 #else
456     return pb_read(stream, (uint8_t*)dest, field->data_size);
457 #endif
458 }
459
460 bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
461 {
462     pb_bytes_array_t *x = (pb_bytes_array_t*)dest;
463     
464     uint32_t temp;
465     if (!pb_decode_varint32(stream, &temp))
466         return false;
467     x->size = temp;
468     
469     if (x->size > field->data_size)
470         return false;
471     
472     return pb_read(stream, x->bytes, x->size);
473 }
474
475 bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
476 {
477     uint32_t size;
478     bool status;
479     if (!pb_decode_varint32(stream, &size))
480         return false;
481     
482     if (size > field->data_size - 1)
483         return false;
484     
485     status = pb_read(stream, (uint8_t*)dest, size);
486     *((uint8_t*)dest + size) = 0;
487     return status;
488 }
489
490 bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
491 {
492     pb_istream_t substream;
493     
494     if (!make_string_substream(stream, &substream))
495         return false;
496     
497     if (field->ptr == NULL)
498         return false;
499     
500     return pb_decode(&substream, (pb_field_t*)field->ptr, dest);
501 }