1 /*
2  * Copyright (c) 2008-2014, Dave Benson and the protobuf-c authors.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  *     * Redistributions in binary form must reproduce the above
13  * copyright notice, this list of conditions and the following disclaimer
14  * in the documentation and/or other materials provided with the
15  * distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*! \file
31  * \mainpage Introduction
32  *
33  * This is [protobuf-c], a C implementation of [Protocol Buffers].
34  *
35  * This file defines the public API for the `libprotobuf-c` support library.
36  * This API includes interfaces that can be used directly by client code as well
37  * as the interfaces used by the code generated by the `protoc-c` compiler.
38  *
39  * The `libprotobuf-c` support library performs the actual serialization and
40  * deserialization of Protocol Buffers messages. It interacts with structures,
41  * definitions, and metadata generated by the `protoc-c` compiler from .proto
42  * files.
43  *
44  * \authors Dave Benson and the `protobuf-c` authors.
45  *
46  * \copyright 2008-2014. Licensed under the terms of the [BSD-2-Clause] license.
47  *
48  * [protobuf-c]:       https://github.com/protobuf-c/protobuf-c
49  * [Protocol Buffers]: https://developers.google.com/protocol-buffers/
50  * [BSD-2-Clause]:     http://opensource.org/licenses/BSD-2-Clause
51  *
52  * \page gencode Generated Code
53  *
54  * For each enum, we generate a C enum. For each message, we generate a C
55  * structure which can be cast to a `ProtobufCMessage`.
56  *
57  * For each enum and message, we generate a descriptor object that allows us to
58  * implement a kind of reflection on the structures.
59  *
60  * First, some naming conventions:
61  *
62  * - The name of the type for enums and messages and services is camel case
63  *   (meaning WordsAreCrammedTogether) except that double underscores are used
64  *   to delimit scopes. For example, the following `.proto` file:
65  *
66 ~~~{.proto}
67         package foo.bar;
68         message BazBah {
69             optional int32 val = 1;
70         }
71 ~~~
72  *
73  * would generate a C type `Foo__Bar__BazBah`.
74  *
75  * - Identifiers for functions and globals are all lowercase, with camel case
76  *   words separated by single underscores. For example, one of the function
77  *   prototypes generated by `protoc-c` for the above example:
78  *
79 ~~~{.c}
80 Foo__Bar__BazBah *
81        foo__bar__baz_bah__unpack
82                      (ProtobufCAllocator  *allocator,
83                       size_t               len,
84                       const uint8_t       *data);
85 ~~~
86  *
87  * - Identifiers for enum values contain an uppercase prefix which embeds the
88  *   package name and the enum type name.
89  *
90  * - A double underscore is used to separate further components of identifier
91  *   names.
92  *
93  * For example, in the name of the unpack function above, the package name
94  * `foo.bar` has become `foo__bar`, the message name BazBah has become
95  * `baz_bah`, and the method name is `unpack`. These are all joined with double
96  * underscores to form the C identifier `foo__bar__baz_bah__unpack`.
97  *
98  * We also generate descriptor objects for messages and enums. These are
99  * declared in the `.pb-c.h` files:
100  *
101 ~~~{.c}
102 extern const ProtobufCMessageDescriptor foo__bar__baz_bah__descriptor;
103 ~~~
104  *
105  * The message structures all begin with `ProtobufCMessageDescriptor *` which is
106  * sufficient to allow them to be cast to `ProtobufCMessage`.
107  *
108  * For each message defined in a `.proto` file, we generate a number of
109  * functions. Each function name contains a prefix based on the package name and
110  * message name in order to make it a unique C identifier.
111  *
112  * - `unpack()`. Unpacks data for a particular message format. Note that the
113  *   `allocator` parameter is usually `NULL` to indicate that the system's
114  *   `malloc()` and `free()` functions should be used for dynamically allocating
115  *   memory.
116  *
117 ~~~{.c}
118 Foo__Bar__BazBah *
119        foo__bar__baz_bah__unpack
120                      (ProtobufCAllocator  *allocator,
121                       size_t               len,
122                       const uint8_t       *data);
123 ~~~
124  *
125  * - `free_unpacked()`. Frees a message object obtained with the `unpack()`
126  *   method.
127  *
128 ~~~{.c}
129 void   foo__bar__baz_bah__free_unpacked
130                      (Foo__Bar__BazBah *message,
131                       ProtobufCAllocator *allocator);
132 ~~~
133  *
134  * - `get_packed_size()`. Calculates the length in bytes of the serialized
135  *   representation of the message object.
136  *
137 ~~~{.c}
138 size_t foo__bar__baz_bah__get_packed_size
139                      (const Foo__Bar__BazBah   *message);
140 ~~~
141  *
142  * - `pack()`. Pack a message object into a preallocated buffer. Assumes that
143  *   the buffer is large enough. (Use `get_packed_size()` first.)
144  *
145 ~~~{.c}
146 size_t foo__bar__baz_bah__pack
147                      (const Foo__Bar__BazBah   *message,
148                       uint8_t             *out);
149 ~~~
150  *
151  * - `pack_to_buffer()`. Packs a message into a "virtual buffer". This is an
152  *   object which defines an "append bytes" callback to consume data as it is
153  *   serialized.
154  *
155 ~~~{.c}
156 size_t foo__bar__baz_bah__pack_to_buffer
157                      (const Foo__Bar__BazBah   *message,
158                       ProtobufCBuffer     *buffer);
159 ~~~
160  *
161  * \page pack Packing and unpacking messages
162  *
163  * To pack a message, first compute the packed size of the message with
164  * protobuf_c_message_get_packed_size(), then allocate a buffer of at least
165  * that size, then call protobuf_c_message_pack().
166  *
167  * Alternatively, a message can be serialized without calculating the final size
168  * first. Use the protobuf_c_message_pack_to_buffer() function and provide a
169  * ProtobufCBuffer object which implements an "append" method that consumes
170  * data.
171  *
172  * To unpack a message, call the protobuf_c_message_unpack() function. The
173  * result can be cast to an object of the type that matches the descriptor for
174  * the message.
175  *
176  * The result of unpacking a message should be freed with
177  * protobuf_c_message_free_unpacked().
178  */
179 
180 #ifndef PROTOBUF_C_H
181 #define PROTOBUF_C_H
182 
183 #include <assert.h>
184 #include <limits.h>
185 #include <stddef.h>
186 #include <stdint.h>
187 
188 #ifdef __cplusplus
189 # define PROTOBUF_C__BEGIN_DECLS	extern "C" {
190 # define PROTOBUF_C__END_DECLS		}
191 #else
192 # define PROTOBUF_C__BEGIN_DECLS
193 # define PROTOBUF_C__END_DECLS
194 #endif
195 
196 PROTOBUF_C__BEGIN_DECLS
197 
198 #if defined(_WIN32) && defined(PROTOBUF_C_USE_SHARED_LIB)
199 # ifdef PROTOBUF_C_EXPORT
200 #  define PROTOBUF_C__API __declspec(dllexport)
201 # else
202 #  define PROTOBUF_C__API __declspec(dllimport)
203 # endif
204 #else
205 # define PROTOBUF_C__API
206 #endif
207 
208 #if !defined(PROTOBUF_C__NO_DEPRECATED) && \
209 	((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
210 # define PROTOBUF_C__DEPRECATED __attribute__((__deprecated__))
211 #else
212 # define PROTOBUF_C__DEPRECATED
213 #endif
214 
215 #ifndef PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE
216  #define PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE(enum_name) \
217   , _##enum_name##_IS_INT_SIZE = INT_MAX
218 #endif
219 
220 #define PROTOBUF_C__SERVICE_DESCRIPTOR_MAGIC    0x14159bc3
221 #define PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC    0x28aaeef9
222 #define PROTOBUF_C__ENUM_DESCRIPTOR_MAGIC       0x114315af
223 
224 /**
225  * \defgroup api Public API
226  *
227  * This is the public API for `libprotobuf-c`. These interfaces are stable and
228  * subject to Semantic Versioning guarantees.
229  *
230  * @{
231  */
232 
233 /**
234  * Values for the `flags` word in `ProtobufCFieldDescriptor`.
235  */
236 typedef enum {
237 	/** Set if the field is repeated and marked with the `packed` option. */
238 	PROTOBUF_C_FIELD_FLAG_PACKED		= (1 << 0),
239 
240 	/** Set if the field is marked with the `deprecated` option. */
241 	PROTOBUF_C_FIELD_FLAG_DEPRECATED	= (1 << 1),
242 } ProtobufCFieldFlag;
243 
244 /**
245  * Message field rules.
246  *
247  * \see [Defining A Message Type] in the Protocol Buffers documentation.
248  *
249  * [Defining A Message Type]:
250  *      https://developers.google.com/protocol-buffers/docs/proto#simple
251  */
252 typedef enum {
253 	/** A well-formed message must have exactly one of this field. */
254 	PROTOBUF_C_LABEL_REQUIRED,
255 
256 	/**
257 	 * A well-formed message can have zero or one of this field (but not
258 	 * more than one).
259 	 */
260 	PROTOBUF_C_LABEL_OPTIONAL,
261 
262 	/**
263 	 * This field can be repeated any number of times (including zero) in a
264 	 * well-formed message. The order of the repeated values will be
265 	 * preserved.
266 	 */
267 	PROTOBUF_C_LABEL_REPEATED,
268 } ProtobufCLabel;
269 
270 /**
271  * Field value types.
272  *
273  * \see [Scalar Value Types] in the Protocol Buffers documentation.
274  *
275  * [Scalar Value Types]:
276  *      https://developers.google.com/protocol-buffers/docs/proto#scalar
277  */
278 typedef enum {
279 	PROTOBUF_C_TYPE_INT32,      /**< int32 */
280 	PROTOBUF_C_TYPE_SINT32,     /**< signed int32 */
281 	PROTOBUF_C_TYPE_SFIXED32,   /**< signed int32 (4 bytes) */
282 	PROTOBUF_C_TYPE_INT64,      /**< int64 */
283 	PROTOBUF_C_TYPE_SINT64,     /**< signed int64 */
284 	PROTOBUF_C_TYPE_SFIXED64,   /**< signed int64 (8 bytes) */
285 	PROTOBUF_C_TYPE_UINT32,     /**< unsigned int32 */
286 	PROTOBUF_C_TYPE_FIXED32,    /**< unsigned int32 (4 bytes) */
287 	PROTOBUF_C_TYPE_UINT64,     /**< unsigned int64 */
288 	PROTOBUF_C_TYPE_FIXED64,    /**< unsigned int64 (8 bytes) */
289 	PROTOBUF_C_TYPE_FLOAT,      /**< float */
290 	PROTOBUF_C_TYPE_DOUBLE,     /**< double */
291 	PROTOBUF_C_TYPE_BOOL,       /**< boolean */
292 	PROTOBUF_C_TYPE_ENUM,       /**< enumerated type */
293 	PROTOBUF_C_TYPE_STRING,     /**< UTF-8 or ASCII string */
294 	PROTOBUF_C_TYPE_BYTES,      /**< arbitrary byte sequence */
295 	PROTOBUF_C_TYPE_MESSAGE,    /**< nested message */
296 } ProtobufCType;
297 
298 /**
299  * Field wire types.
300  *
301  * \see [Message Structure] in the Protocol Buffers documentation.
302  *
303  * [Message Structure]:
304  *      https://developers.google.com/protocol-buffers/docs/encoding#structure
305  */
306 typedef enum {
307 	PROTOBUF_C_WIRE_TYPE_VARINT = 0,
308 	PROTOBUF_C_WIRE_TYPE_64BIT = 1,
309 	PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED = 2,
310 	/* "Start group" and "end group" wire types are unsupported. */
311 	PROTOBUF_C_WIRE_TYPE_32BIT = 5,
312 } ProtobufCWireType;
313 
314 struct ProtobufCAllocator;
315 struct ProtobufCBinaryData;
316 struct ProtobufCBuffer;
317 struct ProtobufCBufferSimple;
318 struct ProtobufCEnumDescriptor;
319 struct ProtobufCEnumValue;
320 struct ProtobufCEnumValueIndex;
321 struct ProtobufCFieldDescriptor;
322 struct ProtobufCIntRange;
323 struct ProtobufCMessage;
324 struct ProtobufCMessageDescriptor;
325 struct ProtobufCMessageUnknownField;
326 struct ProtobufCMethodDescriptor;
327 struct ProtobufCService;
328 struct ProtobufCServiceDescriptor;
329 
330 typedef struct ProtobufCAllocator ProtobufCAllocator;
331 typedef struct ProtobufCBinaryData ProtobufCBinaryData;
332 typedef struct ProtobufCBuffer ProtobufCBuffer;
333 typedef struct ProtobufCBufferSimple ProtobufCBufferSimple;
334 typedef struct ProtobufCEnumDescriptor ProtobufCEnumDescriptor;
335 typedef struct ProtobufCEnumValue ProtobufCEnumValue;
336 typedef struct ProtobufCEnumValueIndex ProtobufCEnumValueIndex;
337 typedef struct ProtobufCFieldDescriptor ProtobufCFieldDescriptor;
338 typedef struct ProtobufCIntRange ProtobufCIntRange;
339 typedef struct ProtobufCMessage ProtobufCMessage;
340 typedef struct ProtobufCMessageDescriptor ProtobufCMessageDescriptor;
341 typedef struct ProtobufCMessageUnknownField ProtobufCMessageUnknownField;
342 typedef struct ProtobufCMethodDescriptor ProtobufCMethodDescriptor;
343 typedef struct ProtobufCService ProtobufCService;
344 typedef struct ProtobufCServiceDescriptor ProtobufCServiceDescriptor;
345 
346 /** Boolean type. */
347 typedef int protobuf_c_boolean;
348 
349 typedef void (*ProtobufCClosure)(const ProtobufCMessage *, void *closure_data);
350 typedef void (*ProtobufCMessageInit)(ProtobufCMessage *);
351 typedef void (*ProtobufCServiceDestroy)(ProtobufCService *);
352 
353 /**
354  * Structure for defining a custom memory allocator.
355  */
356 struct ProtobufCAllocator {
357 	/** Function to allocate memory. */
358 	void		*(*alloc)(void *allocator_data, size_t size);
359 
360 	/** Function to free memory. */
361 	void		(*free)(void *allocator_data, void *pointer);
362 
363 	/** Opaque pointer passed to `alloc` and `free` functions. */
364 	void		*allocator_data;
365 };
366 
367 /**
368  * Structure for the protobuf `bytes` scalar type.
369  *
370  * The data contained in a `ProtobufCBinaryData` is an arbitrary sequence of
371  * bytes. It may contain embedded `NUL` characters and is not required to be
372  * `NUL`-terminated.
373  */
374 struct ProtobufCBinaryData {
375 	size_t	len;        /**< Number of bytes in the `data` field. */
376 	uint8_t	*data;      /**< Data bytes. */
377 };
378 
379 /**
380  * Structure for defining a virtual append-only buffer. Used by
381  * protobuf_c_message_pack_to_buffer() to abstract the consumption of serialized
382  * bytes.
383  *
384  * `ProtobufCBuffer` "subclasses" may be defined on the stack. For example, to
385  * write to a `FILE` object:
386  *
387 ~~~{.c}
388 typedef struct {
389         ProtobufCBuffer base;
390         FILE *fp;
391 } BufferAppendToFile;
392 
393 static void
394 my_buffer_file_append(ProtobufCBuffer *buffer,
395                       size_t len,
396                       const uint8_t *data)
397 {
398         BufferAppendToFile *file_buf = (BufferAppendToFile *) buffer;
399         fwrite(data, len, 1, file_buf->fp); // XXX: No error handling!
400 }
401 ~~~
402  *
403  * To use this new type of ProtobufCBuffer, it could be called as follows:
404  *
405 ~~~{.c}
406 ...
407 BufferAppendToFile tmp = {0};
408 tmp.base.append = my_buffer_file_append;
409 tmp.fp = fp;
410 protobuf_c_message_pack_to_buffer(&message, &tmp);
411 ...
412 ~~~
413  */
414 struct ProtobufCBuffer {
415 	/** Append function. Consumes the `len` bytes stored at `data`. */
416 	void		(*append)(ProtobufCBuffer *buffer,
417 				  size_t len,
418 				  const uint8_t *data);
419 };
420 
421 /**
422  * Simple buffer "subclass" of `ProtobufCBuffer`.
423  *
424  * A `ProtobufCBufferSimple` object is declared on the stack and uses a
425  * scratch buffer provided by the user for the initial allocation. It performs
426  * exponential resizing, using dynamically allocated memory. A
427  * `ProtobufCBufferSimple` object can be created and used as follows:
428  *
429 ~~~{.c}
430 uint8_t pad[128];
431 ProtobufCBufferSimple simple = PROTOBUF_C_BUFFER_SIMPLE_INIT(pad);
432 ProtobufCBuffer *buffer = (ProtobufCBuffer *) &simple;
433 ~~~
434  *
435  * `buffer` can now be used with `protobuf_c_message_pack_to_buffer()`. Once a
436  * message has been serialized to a `ProtobufCBufferSimple` object, the
437  * serialized data bytes can be accessed from the `.data` field.
438  *
439  * To free the memory allocated by a `ProtobufCBufferSimple` object, if any,
440  * call PROTOBUF_C_BUFFER_SIMPLE_CLEAR() on the object, for example:
441  *
442 ~~~{.c}
443 PROTOBUF_C_BUFFER_SIMPLE_CLEAR(&simple);
444 ~~~
445  *
446  * \see PROTOBUF_C_BUFFER_SIMPLE_INIT
447  * \see PROTOBUF_C_BUFFER_SIMPLE_CLEAR
448  */
449 struct ProtobufCBufferSimple {
450 	/** "Base class". */
451 	ProtobufCBuffer		base;
452 	/** Number of bytes allocated in `data`. */
453 	size_t			alloced;
454 	/** Number of bytes currently stored in `data`. */
455 	size_t			len;
456 	/** Data bytes. */
457 	uint8_t			*data;
458 	/** Whether `data` must be freed. */
459 	protobuf_c_boolean	must_free_data;
460 	/** Allocator to use. May be NULL to indicate the system allocator. */
461 	ProtobufCAllocator	*allocator;
462 };
463 
464 /**
465  * Describes an enumeration as a whole, with all of its values.
466  */
467 struct ProtobufCEnumDescriptor {
468 	/** Magic value checked to ensure that the API is used correctly. */
469 	uint32_t			magic;
470 
471 	/** The qualified name (e.g., "namespace.Type"). */
472 	const char			*name;
473 	/** The unqualified name as given in the .proto file (e.g., "Type"). */
474 	const char			*short_name;
475 	/** Identifier used in generated C code. */
476 	const char			*c_name;
477 	/** The dot-separated namespace. */
478 	const char			*package_name;
479 
480 	/** Number elements in `values`. */
481 	unsigned			n_values;
482 	/** Array of distinct values, sorted by numeric value. */
483 	const ProtobufCEnumValue	*values;
484 
485 	/** Number of elements in `values_by_name`. */
486 	unsigned			n_value_names;
487 	/** Array of named values, including aliases, sorted by name. */
488 	const ProtobufCEnumValueIndex	*values_by_name;
489 
490 	/** Number of elements in `value_ranges`. */
491 	unsigned			n_value_ranges;
492 	/** Value ranges, for faster lookups by numeric value. */
493 	const ProtobufCIntRange		*value_ranges;
494 
495 	/** Reserved for future use. */
496 	void				*reserved1;
497 	/** Reserved for future use. */
498 	void				*reserved2;
499 	/** Reserved for future use. */
500 	void				*reserved3;
501 	/** Reserved for future use. */
502 	void				*reserved4;
503 };
504 
505 /**
506  * Represents a single value of an enumeration.
507  */
508 struct ProtobufCEnumValue {
509 	/** The string identifying this value in the .proto file. */
510 	const char	*name;
511 
512 	/** The string identifying this value in generated C code. */
513 	const char	*c_name;
514 
515 	/** The numeric value assigned in the .proto file. */
516 	int		value;
517 };
518 
519 /**
520  * Used by `ProtobufCEnumDescriptor` to look up enum values.
521  */
522 struct ProtobufCEnumValueIndex {
523 	/** Name of the enum value. */
524 	const char      *name;
525 	/** Index into values[] array. */
526 	unsigned        index;
527 };
528 
529 /**
530  * Describes a single field in a message.
531  */
532 struct ProtobufCFieldDescriptor {
533 	/** Name of the field as given in the .proto file. */
534 	const char		*name;
535 
536 	/** Tag value of the field as given in the .proto file. */
537 	uint32_t		id;
538 
539 	/** Whether the field is `REQUIRED`, `OPTIONAL`, or `REPEATED`. */
540 	ProtobufCLabel		label;
541 
542 	/** The type of the field. */
543 	ProtobufCType		type;
544 
545 	/**
546 	 * The offset in bytes of the message's C structure's quantifier field
547 	 * (the `has_MEMBER` field for optional members or the `n_MEMBER` field
548 	 * for repeated members.
549 	 */
550 	unsigned		quantifier_offset;
551 
552 	/**
553 	 * The offset in bytes into the message's C structure for the member
554 	 * itself.
555 	 */
556 	unsigned		offset;
557 
558 	/**
559 	 * A type-specific descriptor.
560 	 *
561 	 * If `type` is `PROTOBUF_C_TYPE_ENUM`, then `descriptor` points to the
562 	 * corresponding `ProtobufCEnumDescriptor`.
563 	 *
564 	 * If `type` is `PROTOBUF_C_TYPE_MESSAGE`, then `descriptor` points to
565 	 * the corresponding `ProtobufCMessageDescriptor`.
566 	 *
567 	 * Otherwise this field is NULL.
568 	 */
569 	const void		*descriptor; /* for MESSAGE and ENUM types */
570 
571 	/** The default value for this field, if defined. May be NULL. */
572 	const void		*default_value;
573 
574 	/**
575 	 * A flag word. Zero or more of the bits defined in the
576 	 * `ProtobufCFieldFlag` enum may be set.
577 	 */
578 	uint32_t		flags;
579 
580 	/** Reserved for future use. */
581 	unsigned		reserved_flags;
582 	/** Reserved for future use. */
583 	void			*reserved2;
584 	/** Reserved for future use. */
585 	void			*reserved3;
586 };
587 
588 /**
589  * Helper structure for optimizing int => index lookups in the case
590  * where the keys are mostly consecutive values, as they presumably are for
591  * enums and fields.
592  *
593  * The data structures requires that the values in the original array are
594  * sorted.
595  */
596 struct ProtobufCIntRange {
597 	int             start_value;
598 	unsigned        orig_index;
599 	/*
600 	 * NOTE: the number of values in the range can be inferred by looking
601 	 * at the next element's orig_index. A dummy element is added to make
602 	 * this simple.
603 	 */
604 };
605 
606 /**
607  * An instance of a message.
608  *
609  * `ProtobufCMessage` is a light-weight "base class" for all messages.
610  *
611  * In particular, `ProtobufCMessage` doesn't have any allocation policy
612  * associated with it. That's because it's common to create `ProtobufCMessage`
613  * objects on the stack. In fact, that's what we recommend for sending messages.
614  * If the object is allocated from the stack, you can't really have a memory
615  * leak.
616  *
617  * This means that calls to functions like protobuf_c_message_unpack() which
618  * return a `ProtobufCMessage` must be paired with a call to a free function,
619  * like protobuf_c_message_free_unpacked().
620  */
621 struct ProtobufCMessage {
622 	/** The descriptor for this message type. */
623 	const ProtobufCMessageDescriptor	*descriptor;
624 	/** The number of elements in `unknown_fields`. */
625 	unsigned				n_unknown_fields;
626 	/** The fields that weren't recognized by the parser. */
627 	ProtobufCMessageUnknownField		*unknown_fields;
628 };
629 
630 /**
631  * Describes a message.
632  */
633 struct ProtobufCMessageDescriptor {
634 	/** Magic value checked to ensure that the API is used correctly. */
635 	uint32_t			magic;
636 
637 	/** The qualified name (e.g., "namespace.Type"). */
638 	const char			*name;
639 	/** The unqualified name as given in the .proto file (e.g., "Type"). */
640 	const char			*short_name;
641 	/** Identifier used in generated C code. */
642 	const char			*c_name;
643 	/** The dot-separated namespace. */
644 	const char			*package_name;
645 
646 	/**
647 	 * Size in bytes of the C structure representing an instance of this
648 	 * type of message.
649 	 */
650 	size_t				sizeof_message;
651 
652 	/** Number of elements in `fields`. */
653 	unsigned			n_fields;
654 	/** Field descriptors, sorted by tag number. */
655 	const ProtobufCFieldDescriptor	*fields;
656 	/** Used for looking up fields by name. */
657 	const unsigned			*fields_sorted_by_name;
658 
659 	/** Number of elements in `field_ranges`. */
660 	unsigned			n_field_ranges;
661 	/** Used for looking up fields by id. */
662 	const ProtobufCIntRange		*field_ranges;
663 
664 	/** Message initialisation function. */
665 	ProtobufCMessageInit		message_init;
666 
667 	/** Reserved for future use. */
668 	void				*reserved1;
669 	/** Reserved for future use. */
670 	void				*reserved2;
671 	/** Reserved for future use. */
672 	void				*reserved3;
673 };
674 
675 /**
676  * An unknown message field.
677  */
678 struct ProtobufCMessageUnknownField {
679 	/** The tag number. */
680 	uint32_t		tag;
681 	/** The wire type of the field. */
682 	ProtobufCWireType	wire_type;
683 	/** Number of bytes in `data`. */
684 	size_t			len;
685 	/** Field data. */
686 	uint8_t			*data;
687 };
688 
689 /**
690  * Method descriptor.
691  */
692 struct ProtobufCMethodDescriptor {
693 	/** Method name. */
694 	const char				*name;
695 	/** Input message descriptor. */
696 	const ProtobufCMessageDescriptor	*input;
697 	/** Output message descriptor. */
698 	const ProtobufCMessageDescriptor	*output;
699 };
700 
701 /**
702  * Service.
703  */
704 struct ProtobufCService {
705 	/** Service descriptor. */
706 	const ProtobufCServiceDescriptor *descriptor;
707 	/** Function to invoke the service. */
708 	void (*invoke)(ProtobufCService *service,
709 		       unsigned method_index,
710 		       const ProtobufCMessage *input,
711 		       ProtobufCClosure closure,
712 		       void *closure_data);
713 	/** Function to destroy the service. */
714 	void (*destroy)(ProtobufCService *service);
715 };
716 
717 /**
718  * Service descriptor.
719  */
720 struct ProtobufCServiceDescriptor {
721 	/** Magic value checked to ensure that the API is used correctly. */
722 	uint32_t			magic;
723 
724 	/** Service name. */
725 	const char			*name;
726 	/** Short version of service name. */
727 	const char			*short_name;
728 	/** C identifier for the service name. */
729 	const char			*c_name;
730 	/** Package name. */
731 	const char			*package;
732 	/** Number of elements in `methods`. */
733 	unsigned			n_methods;
734 	/** Method descriptors, in the order defined in the .proto file. */
735 	const ProtobufCMethodDescriptor	*methods;
736 	/** Sort index of methods. */
737 	const unsigned			*method_indices_by_name;
738 };
739 
740 /**
741  * Get the version of the protobuf-c library. Note that this is the version of
742  * the library linked against, not the version of the headers compiled against.
743  *
744  * \return A string containing the version number of protobuf-c.
745  */
746 PROTOBUF_C__API
747 const char *
748 protobuf_c_version(void);
749 
750 /**
751  * Get the version of the protobuf-c library. Note that this is the version of
752  * the library linked against, not the version of the headers compiled against.
753  *
754  * \return A 32 bit unsigned integer containing the version number of
755  *      protobuf-c, represented in base-10 as (MAJOR*1E6) + (MINOR*1E3) + PATCH.
756  */
757 PROTOBUF_C__API
758 uint32_t
759 protobuf_c_version_number(void);
760 
761 /**
762  * The version of the protobuf-c headers, represented as a string using the same
763  * format as protobuf_c_version().
764  */
765 #define PROTOBUF_C_VERSION		"1.0.2"
766 
767 /**
768  * The version of the protobuf-c headers, represented as an integer using the
769  * same format as protobuf_c_version_number().
770  */
771 #define PROTOBUF_C_VERSION_NUMBER	1000002
772 
773 /**
774  * The minimum protoc-c version which works with the current version of the
775  * protobuf-c headers.
776  */
777 #define PROTOBUF_C_MIN_COMPILER_VERSION	1000000
778 
779 /**
780  * Look up a `ProtobufCEnumValue` from a `ProtobufCEnumDescriptor` by name.
781  *
782  * \param desc
783  *      The `ProtobufCEnumDescriptor` object.
784  * \param name
785  *      The `name` field from the corresponding `ProtobufCEnumValue` object to
786  *      match.
787  * \return
788  *      A `ProtobufCEnumValue` object.
789  * \retval NULL
790  *      If not found.
791  */
792 PROTOBUF_C__API
793 const ProtobufCEnumValue *
794 protobuf_c_enum_descriptor_get_value_by_name(
795 	const ProtobufCEnumDescriptor *desc,
796 	const char *name);
797 
798 /**
799  * Look up a `ProtobufCEnumValue` from a `ProtobufCEnumDescriptor` by numeric
800  * value.
801  *
802  * \param desc
803  *      The `ProtobufCEnumDescriptor` object.
804  * \param value
805  *      The `value` field from the corresponding `ProtobufCEnumValue` object to
806  *      match.
807  *
808  * \return
809  *      A `ProtobufCEnumValue` object.
810  * \retval NULL
811  *      If not found.
812  */
813 PROTOBUF_C__API
814 const ProtobufCEnumValue *
815 protobuf_c_enum_descriptor_get_value(
816 	const ProtobufCEnumDescriptor *desc,
817 	int value);
818 
819 /**
820  * Look up a `ProtobufCFieldDescriptor` from a `ProtobufCMessageDescriptor` by
821  * the name of the field.
822  *
823  * \param desc
824  *      The `ProtobufCMessageDescriptor` object.
825  * \param name
826  *      The name of the field.
827  * \return
828  *      A `ProtobufCFieldDescriptor` object.
829  * \retval NULL
830  *      If not found.
831  */
832 PROTOBUF_C__API
833 const ProtobufCFieldDescriptor *
834 protobuf_c_message_descriptor_get_field_by_name(
835 	const ProtobufCMessageDescriptor *desc,
836 	const char *name);
837 
838 /**
839  * Look up a `ProtobufCFieldDescriptor` from a `ProtobufCMessageDescriptor` by
840  * the tag value of the field.
841  *
842  * \param desc
843  *      The `ProtobufCMessageDescriptor` object.
844  * \param value
845  *      The tag value of the field.
846  * \return
847  *      A `ProtobufCFieldDescriptor` object.
848  * \retval NULL
849  *      If not found.
850  */
851 PROTOBUF_C__API
852 const ProtobufCFieldDescriptor *
853 protobuf_c_message_descriptor_get_field(
854 	const ProtobufCMessageDescriptor *desc,
855 	unsigned value);
856 
857 /**
858  * Determine the number of bytes required to store the serialised message.
859  *
860  * \param message
861  *      The message object to serialise.
862  * \return
863  *      Number of bytes.
864  */
865 PROTOBUF_C__API
866 size_t
867 protobuf_c_message_get_packed_size(const ProtobufCMessage *message);
868 
869 /**
870  * Serialise a message from its in-memory representation.
871  *
872  * This function stores the serialised bytes of the message in a pre-allocated
873  * buffer.
874  *
875  * \param message
876  *      The message object to serialise.
877  * \param[out] out
878  *      Buffer to store the bytes of the serialised message. This buffer must
879  *      have enough space to store the packed message. Use
880  *      protobuf_c_message_get_packed_size() to determine the number of bytes
881  *      required.
882  * \return
883  *      Number of bytes stored in `out`.
884  */
885 PROTOBUF_C__API
886 size_t
887 protobuf_c_message_pack(const ProtobufCMessage *message, uint8_t *out);
888 
889 /**
890  * Serialise a message from its in-memory representation to a virtual buffer.
891  *
892  * This function calls the `append` method of a `ProtobufCBuffer` object to
893  * consume the bytes generated by the serialiser.
894  *
895  * \param message
896  *      The message object to serialise.
897  * \param buffer
898  *      The virtual buffer object.
899  * \return
900  *      Number of bytes passed to the virtual buffer.
901  */
902 PROTOBUF_C__API
903 size_t
904 protobuf_c_message_pack_to_buffer(
905 	const ProtobufCMessage *message,
906 	ProtobufCBuffer *buffer);
907 
908 /**
909  * Unpack a serialised message into an in-memory representation.
910  *
911  * \param descriptor
912  *      The message descriptor.
913  * \param allocator
914  *      `ProtobufCAllocator` to use for memory allocation. May be NULL to
915  *      specify the default allocator.
916  * \param len
917  *      Length in bytes of the serialised message.
918  * \param data
919  *      Pointer to the serialised message.
920  * \return
921  *      An unpacked message object.
922  * \retval NULL
923  *      If an error occurred during unpacking.
924  */
925 PROTOBUF_C__API
926 ProtobufCMessage *
927 protobuf_c_message_unpack(
928 	const ProtobufCMessageDescriptor *descriptor,
929 	ProtobufCAllocator *allocator,
930 	size_t len,
931 	const uint8_t *data);
932 
933 /**
934  * Free an unpacked message object.
935  *
936  * This function should be used to deallocate the memory used by a call to
937  * protobuf_c_message_unpack().
938  *
939  * \param message
940  *      The message object to free.
941  * \param allocator
942  *      `ProtobufCAllocator` to use for memory deallocation. May be NULL to
943  *      specify the default allocator.
944  */
945 PROTOBUF_C__API
946 void
947 protobuf_c_message_free_unpacked(
948 	ProtobufCMessage *message,
949 	ProtobufCAllocator *allocator);
950 
951 /**
952  * Check the validity of a message object.
953  *
954  * Makes sure all required fields (`PROTOBUF_C_LABEL_REQUIRED`) are present.
955  * Recursively checks nested messages.
956  *
957  * \retval TRUE
958  *      Message is valid.
959  * \retval FALSE
960  *      Message is invalid.
961  */
962 PROTOBUF_C__API
963 protobuf_c_boolean
964 protobuf_c_message_check(const ProtobufCMessage *);
965 
966 /** Message initialiser. */
967 #define PROTOBUF_C_MESSAGE_INIT(descriptor) { descriptor, 0, NULL }
968 
969 /**
970  * Initialise a message object from a message descriptor.
971  *
972  * \param descriptor
973  *      Message descriptor.
974  * \param message
975  *      Allocated block of memory of size `descriptor->sizeof_message`.
976  */
977 PROTOBUF_C__API
978 void
979 protobuf_c_message_init(
980 	const ProtobufCMessageDescriptor *descriptor,
981 	void *message);
982 
983 /**
984  * Free a service.
985  *
986  * \param service
987  *      The service object to free.
988  */
989 PROTOBUF_C__API
990 void
991 protobuf_c_service_destroy(ProtobufCService *service);
992 
993 /**
994  * Look up a `ProtobufCMethodDescriptor` by name.
995  *
996  * \param desc
997  *      Service descriptor.
998  * \param name
999  *      Name of the method.
1000  *
1001  * \return
1002  *      A `ProtobufCMethodDescriptor` object.
1003  * \retval NULL
1004  *      If not found.
1005  */
1006 PROTOBUF_C__API
1007 const ProtobufCMethodDescriptor *
1008 protobuf_c_service_descriptor_get_method_by_name(
1009 	const ProtobufCServiceDescriptor *desc,
1010 	const char *name);
1011 
1012 /**
1013  * Initialise a `ProtobufCBufferSimple` object.
1014  */
1015 #define PROTOBUF_C_BUFFER_SIMPLE_INIT(array_of_bytes)                   \
1016 {                                                                       \
1017 	{ protobuf_c_buffer_simple_append },                            \
1018 	sizeof(array_of_bytes),                                         \
1019 	0,                                                              \
1020 	(array_of_bytes),                                               \
1021 	0,                                                              \
1022 	NULL                                                            \
1023 }
1024 
1025 /**
1026  * Clear a `ProtobufCBufferSimple` object, freeing any allocated memory.
1027  */
1028 #define PROTOBUF_C_BUFFER_SIMPLE_CLEAR(simp_buf)                        \
1029 do {                                                                    \
1030 	if ((simp_buf)->must_free_data) {                               \
1031 		if ((simp_buf)->allocator != NULL)                      \
1032 			(simp_buf)->allocator->free(                    \
1033 				(simp_buf)->allocator,                  \
1034 				(simp_buf)->data);			\
1035 		else                                                    \
1036 			free((simp_buf)->data);                         \
1037 	}                                                               \
1038 } while (0)
1039 
1040 /**
1041  * The `append` method for `ProtobufCBufferSimple`.
1042  *
1043  * \param buffer
1044  *      The buffer object to append to. Must actually be a
1045  *      `ProtobufCBufferSimple` object.
1046  * \param len
1047  *      Number of bytes in `data`.
1048  * \param data
1049  *      Data to append.
1050  */
1051 PROTOBUF_C__API
1052 void
1053 protobuf_c_buffer_simple_append(
1054 	ProtobufCBuffer *buffer,
1055 	size_t len,
1056 	const unsigned char *data);
1057 
1058 PROTOBUF_C__API
1059 void
1060 protobuf_c_service_generated_init(
1061 	ProtobufCService *service,
1062 	const ProtobufCServiceDescriptor *descriptor,
1063 	ProtobufCServiceDestroy destroy);
1064 
1065 PROTOBUF_C__API
1066 void
1067 protobuf_c_service_invoke_internal(
1068 	ProtobufCService *service,
1069 	unsigned method_index,
1070 	const ProtobufCMessage *input,
1071 	ProtobufCClosure closure,
1072 	void *closure_data);
1073 
1074 /**@}*/
1075 
1076 PROTOBUF_C__END_DECLS
1077 
1078 #endif /* PROTOBUF_C_H */
1079