gnunetutil: add 2d and 3d allocation including tests
[oweals/gnunet.git] / src / include / gnunet_mq_lib.h
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012-2016 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @author Florian Dold
23  * @author Christian Grothoff
24  *
25  * @file
26  * General-purpose message queue
27  *
28  * @defgroup mq  MQ library
29  * General-purpose message queue
30  *
31  * @see [Documentation](https://gnunet.org/message-queue-api)
32  *
33  * @{
34  */
35 #ifndef GNUNET_MQ_H
36 #define GNUNET_MQ_H
37
38
39 /**
40  * Allocate an envelope, with extra space allocated after the space needed
41  * by the message struct.
42  * The allocated message will already have the type and size field set.
43  *
44  * @param mvar variable to store the allocated message in;
45  *             must have a header field
46  * @param esize extra space to allocate after the message
47  * @param type type of the message
48  * @return the MQ message
49  */
50 #define GNUNET_MQ_msg_extra(mvar, esize, type) GNUNET_MQ_msg_(((struct GNUNET_MessageHeader**) &(mvar)), (esize) + sizeof *(mvar), (type))
51
52 /**
53  * Allocate a GNUNET_MQ_Envelope.
54  * The contained message will already have the type and size field set.
55  *
56  * @param mvar variable to store the allocated message in;
57  *             must have a header field
58  * @param type type of the message
59  * @return the allocated envelope
60  */
61 #define GNUNET_MQ_msg(mvar, type) GNUNET_MQ_msg_extra(mvar, 0, type)
62
63
64 /**
65  * Allocate a GNUNET_MQ_Envelope, where the message only consists of a header.
66  * The allocated message will already have the type and size field set.
67  *
68  * @param type type of the message
69  */
70 #define GNUNET_MQ_msg_header(type) GNUNET_MQ_msg_ (NULL, sizeof (struct GNUNET_MessageHeader), type)
71
72
73 /**
74  * Allocate a GNUNET_MQ_Envelope, where the message only consists of a header and extra space.
75  * The allocated message will already have the type and size field set.
76  *
77  * @param mh pointer that will changed to point at to the allocated message header
78  * @param esize extra space to allocate after the message header
79  * @param type type of the message
80  */
81 #define GNUNET_MQ_msg_header_extra(mh, esize, type) GNUNET_MQ_msg_ (&mh, (esize) + sizeof (struct GNUNET_MessageHeader), type)
82
83
84 /**
85  * Allocate a GNUNET_MQ_Envelope, and append a payload message after the given
86  * message struct.
87  *
88  * @param mvar pointer to a message struct, will be changed to point at the newly allocated message,
89  *        whose size is 'sizeof(*mvar) + ntohs (mh->size)'
90  * @param type message type of the allocated message, has no effect on the nested message
91  * @param mh message to nest
92  * @return a newly allocated 'struct GNUNET_MQ_Envelope *'
93  */
94 #define GNUNET_MQ_msg_nested_mh(mvar, type, mh) GNUNET_MQ_msg_nested_mh_((((void)(mvar)->header), (struct GNUNET_MessageHeader**) &(mvar)), sizeof (*(mvar)), (type), mh)
95
96
97 /**
98  * Return a pointer to the message at the end of the given message.
99  *
100  * @param var pointer to a message struct, the type of the expression determines the base size,
101  *        the space after the base size is the nested message
102  * @return a 'struct GNUNET_MessageHeader *' that points at the nested message of the given message,
103  *         or NULL if the given message in @a var does not have any space after the message struct
104  */
105 #define GNUNET_MQ_extract_nested_mh(var) GNUNET_MQ_extract_nested_mh_ ((struct GNUNET_MessageHeader *) (var), sizeof (*(var)))
106
107
108 /**
109  * Implementation of the #GNUNET_MQ_extract_nexted_mh macro.
110  *
111  * @param mh message header to extract nested message header from
112  * @param base_size size of the message before the nested message's header appears
113  * @return pointer to the nested message, does not copy the message
114  */
115 const struct GNUNET_MessageHeader *
116 GNUNET_MQ_extract_nested_mh_ (const struct GNUNET_MessageHeader *mh,
117                               uint16_t base_size);
118
119
120 /**
121  * Opaque handle to an envelope.
122  */
123 struct GNUNET_MQ_Envelope;
124
125
126 /**
127  * Implementation of the #GNUNET_MQ_msg_nested_mh macro.
128  *
129  * @param mhp pointer to the message header pointer that will be changed to allocate at
130  *        the newly allocated space for the message.
131  * @param base_size size of the data before the nested message
132  * @param type type of the message in the envelope
133  * @param nested_mh the message to append to the message after base_size
134  */
135 struct GNUNET_MQ_Envelope *
136 GNUNET_MQ_msg_nested_mh_ (struct GNUNET_MessageHeader **mhp,
137                           uint16_t base_size,
138                           uint16_t type,
139                           const struct GNUNET_MessageHeader *nested_mh);
140
141
142 /**
143  * Opaque handle to a message queue.
144  */
145 struct GNUNET_MQ_Handle;
146
147
148 /**
149  * Error codes for the queue.
150  */
151 enum GNUNET_MQ_Error
152 {
153   /**
154    * Failed to read message from the network.
155    * FIXME: Likely not properly distinguished
156    * from TIMEOUT case in the code!
157    */
158   GNUNET_MQ_ERROR_READ = 1,
159
160   /**
161    * FIXME: document!
162    */
163   GNUNET_MQ_ERROR_WRITE = 2,
164
165   /**
166    * FIXME: document!
167    */
168   GNUNET_MQ_ERROR_TIMEOUT = 4,
169
170   /**
171    * We received a message that was malformed and thus
172    * could not be passed to its handler.
173    */
174   GNUNET_MQ_ERROR_MALFORMED = 8
175 };
176
177
178 /**
179  * Called when a message has been received.
180  *
181  * @param cls closure
182  * @param msg the received message
183  */
184 typedef void
185 (*GNUNET_MQ_MessageCallback) (void *cls,
186                               const struct GNUNET_MessageHeader *msg);
187
188
189 /**
190  * Called when a message needs to be validated.
191  *
192  * @param cls closure
193  * @param msg the received message
194  * @return #GNUNET_OK if the message is well-formed,
195  *         #GNUNET_SYSERR if not
196  */
197 typedef int
198 (*GNUNET_MQ_MessageValidationCallback) (void *cls,
199                                         const struct GNUNET_MessageHeader *msg);
200
201
202 /**
203  * Signature of functions implementing the
204  * sending functionality of a message queue.
205  *
206  * @param mq the message queue
207  * @param msg the message to send
208  * @param impl_state state of the implementation
209  */
210 typedef void
211 (*GNUNET_MQ_SendImpl) (struct GNUNET_MQ_Handle *mq,
212                        const struct GNUNET_MessageHeader *msg,
213                        void *impl_state);
214
215
216 /**
217  * Signature of functions implementing the
218  * destruction of a message queue.
219  * Implementations must not free @a mq, but should
220  * take care of @a impl_state.
221  *
222  * @param mq the message queue to destroy
223  * @param impl_state state of the implementation
224  */
225 typedef void
226 (*GNUNET_MQ_DestroyImpl) (struct GNUNET_MQ_Handle *mq,
227                           void *impl_state);
228
229
230 /**
231  * Implementation function that cancels the currently sent message.
232  *
233  * @param mq message queue
234  * @param impl_state state specific to the implementation
235  */
236 typedef void
237 (*GNUNET_MQ_CancelImpl) (struct GNUNET_MQ_Handle *mq,
238                          void *impl_state);
239
240
241 /**
242  * Callback used for notifications
243  *
244  * @param cls closure
245  */
246 typedef void
247 (*GNUNET_MQ_NotifyCallback) (void *cls);
248
249
250 /**
251  * Generic error handler, called with the appropriate
252  * error code and the same closure specified at the creation of
253  * the message queue.
254  * Not every message queue implementation supports an error handler.
255  *
256  * @param cls closure
257  * @param error error code
258  */
259 typedef void
260 (*GNUNET_MQ_ErrorHandler) (void *cls,
261                            enum GNUNET_MQ_Error error);
262
263
264 /**
265  * Message handler for a specific message type.
266  */
267 struct GNUNET_MQ_MessageHandler
268 {
269   /**
270    * Callback to validate a message of the specified @e type.
271    * The closure given to @e mv will be this struct (not @e ctx).
272    * Using NULL means only size-validation using
273    * @e expected_size.  In this case, @e expected_size must
274    * be non-zero.
275    */
276   GNUNET_MQ_MessageValidationCallback mv;
277
278   /**
279    * Callback, called every time a new message of
280    * the specified @e type has been receied.
281    * The closure given to @e mv will be this struct (not @e ctx).
282    */
283   GNUNET_MQ_MessageCallback cb;
284
285   /**
286    * Closure for @e mv and @e cb.
287    */
288   void *cls;
289
290   /**
291    * Type of the message this handler covers, in host byte order.
292    */
293   uint16_t type;
294
295   /**
296    * Expected size of messages of this type.  Minimum size of the
297    * message if @e mv is non-NULL.  Messages of the given type will be
298    * discarded (and the connection closed with an error reported to
299    * the application) if they do not have the right size.
300    */
301   uint16_t expected_size;
302 };
303
304
305 /**
306  * End-marker for the handlers array
307  */
308 #define GNUNET_MQ_handler_end() { NULL, NULL, NULL, 0, 0 }
309
310
311 /**
312  * Defines a static function @a name which takes as a single argument
313  * a message handler for fixed-sized messages of type @a code and with
314  * a message type argument of @a str.  Given such an argument, the
315  * function @name will return a `struct GNUNET_MQ_MessageHandler`
316  * for the given message type.
317  *
318  * The macro is to be used as follows:
319  * <code>
320  * struct GNUNET_MessageTest { ... }; // must be fixed size
321  * static void
322  * handle_test_message (void *cls,
323  *                      const struct GNUNET_MessageTest *msg)
324  * { ... }
325  *
326  * struct GNUNET_MQ_MessageHandler handlers[] = {
327  *   GNUNET_MQ_hd_fixed_size(test_message,
328  *                           GNUNET_MESSAGE_TYPE_TEST,
329  *                           struct GNUNET_MessageTest,
330  *                           "context"),
331  *   GNUNET_MQ_handler_end()
332  * };
333  *
334  * @param name unique basename for the functions
335  * @param code message type constant
336  * @param str type of the message (a struct)
337  * @param ctx context for the callbacks
338  */
339 #define GNUNET_MQ_hd_fixed_size(name,code,str,ctx)           \
340   ({                                                         \
341     void (*_cb)(void *cls, const str *msg) = &handle_##name; \
342     ((struct GNUNET_MQ_MessageHandler) {                     \
343       NULL, (GNUNET_MQ_MessageCallback) _cb,                 \
344       (ctx), (code), sizeof (str) });                        \
345   })
346
347
348 /**
349  * Defines a static function @a name which takes two arguments and a
350  * context-pointer for validating and handling variable-sized messages
351  * of type @a code and with a message type argument of @a str.  Given
352  * such arguments, the function @name will return a `struct
353  * GNUNET_MQ_MessageHandler` for the given message type.
354  *
355  * The macro is to be used as follows:
356  * <code>
357  * struct GNUNET_MessageTest { ... }; // can be variable size
358  * static int
359  * check_test (void *cls,
360  *             const struct GNUNET_MessageTest *msg)
361  * {
362  *   const char *ctx = cls;
363  *   GNUNET_assert (0 == strcmp ("context", ctx));
364  *   // ...
365  * }
366  * static void
367  * handle_test (void *cls,
368  *              const struct GNUNET_MessageTest *msg)
369  * {
370  *   const char *ctx = cls;
371  *   GNUNET_assert (0 == strcmp ("context", ctx));
372  *   // ...
373  * }
374  *
375  * struct GNUNET_MQ_MessageHandler handlers[] = {
376  *   GNUNET_MQ_hd_var_size(test_message,
377  *                         GNUNET_MESSAGE_TYPE_TEST,
378  *                         struct GNUNET_MessageTest,
379  *                         "context"),
380  *   GNUNET_MQ_handler_end()
381  * };
382  *
383  * @param name unique basename for the functions
384  * @param code message type constant
385  * @param str type of the message (a struct)
386  * @param ctx context for the callbacks
387  */
388 #define GNUNET_MQ_hd_var_size(name,code,str,ctx)             \
389   ({                                                         \
390     int (*_mv)(void *cls, const str *msg) = &check_##name;   \
391     void (*_cb)(void *cls, const str *msg) = &handle_##name; \
392     ((struct GNUNET_MQ_MessageHandler)                       \
393       { (GNUNET_MQ_MessageValidationCallback) _mv,           \
394         (GNUNET_MQ_MessageCallback) _cb,                     \
395         (ctx), (code), sizeof (str) });                      \
396   })
397
398
399 /**
400  * Create a new envelope.
401  *
402  * @param mhp message header to store the allocated message header in, can be NULL
403  * @param size size of the message to allocate
404  * @param type type of the message, will be set in the allocated message
405  * @return the allocated MQ message
406  */
407 struct GNUNET_MQ_Envelope *
408 GNUNET_MQ_msg_ (struct GNUNET_MessageHeader **mhp,
409                 uint16_t size,
410                 uint16_t type);
411
412
413 /**
414  * Create a new envelope by copying an existing message.
415  *
416  * @param hdr header of the message to copy
417  * @return envelope containing @a hdr
418  */
419 struct GNUNET_MQ_Envelope *
420 GNUNET_MQ_msg_copy (const struct GNUNET_MessageHeader *hdr);
421
422
423 /**
424  * Discard the message queue message, free all
425  * allocated resources. Must be called in the event
426  * that a message is created but should not actually be sent.
427  *
428  * @param mqm the message to discard
429  */
430 void
431 GNUNET_MQ_discard (struct GNUNET_MQ_Envelope *mqm);
432
433
434 /**
435  * Function to obtain the current envelope
436  * from within #GNUNET_MQ_SendImpl implementations.
437  *
438  * @param mq message queue to interrogate
439  * @return the current envelope
440  */
441 struct GNUNET_MQ_Envelope *
442 GNUNET_MQ_get_current_envelope (struct GNUNET_MQ_Handle *mq);
443
444
445 /**
446  * Function to obtain the last envelope in the queue.
447  *
448  * @param mq message queue to interrogate
449  * @return the last envelope in the queue
450  */
451 struct GNUNET_MQ_Envelope *
452 GNUNET_MQ_get_last_envelope (struct GNUNET_MQ_Handle *mq);
453
454
455 /**
456  * Set application-specific options for this envelope.
457  * Overrides the options set for the queue with
458  * #GNUNET_MQ_set_options() for this message only.
459  *
460  * @param env message to set options for
461  * @param flags flags to use (meaning is queue-specific)
462  * @param extra additional buffer for further data (also queue-specific)
463  */
464 void
465 GNUNET_MQ_env_set_options (struct GNUNET_MQ_Envelope *env,
466                            uint64_t flags,
467                            const void *extra);
468
469
470 /**
471  * Get application-specific options for this envelope.
472  *
473  * @param env message to set options for
474  * @param[out] flags set to flags to use (meaning is queue-specific)
475  * @return extra additional buffer for further data (also queue-specific)
476  */
477 const void *
478 GNUNET_MQ_env_get_options (struct GNUNET_MQ_Envelope *env,
479                            uint64_t *flags);
480
481
482 /**
483  * Set application-specific options for this queue.
484  *
485  * @param mq message queue to set options for
486  * @param flags flags to use (meaning is queue-specific)
487  * @param extra additional buffer for further data (also queue-specific)
488  */
489 void
490 GNUNET_MQ_set_options (struct GNUNET_MQ_Handle *mq,
491                        uint64_t flags,
492                        const void *extra);
493
494
495 /**
496  * Obtain the current length of the message queue.
497  *
498  * @param mq queue to inspect
499  * @return number of queued, non-transmitted messages
500  */
501 unsigned int
502 GNUNET_MQ_get_length (struct GNUNET_MQ_Handle *mq);
503
504
505 /**
506  * Send a message with the given message queue.
507  * May only be called once per message.
508  *
509  * @param mq message queue
510  * @param ev the envelope with the message to send.
511  */
512 void
513 GNUNET_MQ_send (struct GNUNET_MQ_Handle *mq,
514                 struct GNUNET_MQ_Envelope *ev);
515
516
517 /**
518  * Send a copy of a message with the given message queue.
519  * Can be called repeatedly on the same envelope.
520  *
521  * @param mq message queue
522  * @param ev the envelope with the message to send.
523  */
524 void
525 GNUNET_MQ_send_copy (struct GNUNET_MQ_Handle *mq,
526                      const struct GNUNET_MQ_Envelope *ev);
527
528
529 /**
530  * Cancel sending the message. Message must have been sent with
531  * #GNUNET_MQ_send before.  May not be called after the notify sent
532  * callback has been called
533  *
534  * @param ev queued envelope to cancel
535  */
536 void
537 GNUNET_MQ_send_cancel (struct GNUNET_MQ_Envelope *ev);
538
539
540 /**
541  * Associate the assoc_data in @a mq with a unique request id.
542  *
543  * @param mq message queue, id will be unique for the queue
544  * @param assoc_data to associate
545  */
546 uint32_t
547 GNUNET_MQ_assoc_add (struct GNUNET_MQ_Handle *mq,
548                      void *assoc_data);
549
550
551 /**
552  * Get the data associated with a @a request_id in a queue
553  *
554  * @param mq the message queue with the association
555  * @param request_id the request id we are interested in
556  * @return the associated data
557  */
558 void *
559 GNUNET_MQ_assoc_get (struct GNUNET_MQ_Handle *mq,
560                      uint32_t request_id);
561
562
563 /**
564  * Remove the association for a @a request_id
565  *
566  * @param mq the message queue with the association
567  * @param request_id the request id we want to remove
568  * @return the associated data
569  */
570 void *
571 GNUNET_MQ_assoc_remove (struct GNUNET_MQ_Handle *mq,
572                         uint32_t request_id);
573
574
575 /**
576  * Create a message queue for the specified handlers.
577  *
578  * @param send function the implements sending messages
579  * @param destroy function that implements destroying the queue
580  * @param cancel function that implements canceling a message
581  * @param impl_state for the queue, passed to @a send, @a destroy and @a cancel
582  * @param handlers array of message handlers
583  * @param error_handler handler for read and write errors
584  * @param cls closure for message handlers and error handler
585  * @return a new message queue
586  */
587 struct GNUNET_MQ_Handle *
588 GNUNET_MQ_queue_for_callbacks (GNUNET_MQ_SendImpl send,
589                                GNUNET_MQ_DestroyImpl destroy,
590                                GNUNET_MQ_CancelImpl cancel,
591                                void *impl_state,
592                                const struct GNUNET_MQ_MessageHandler *handlers,
593                                GNUNET_MQ_ErrorHandler error_handler,
594                                void *cls);
595
596
597 /**
598  * Change the closure argument in all of the `handlers` of the
599  * @a mq.
600  *
601  * @param mq to modify
602  * @param handlers_cls new closure to use
603  */
604 void
605 GNUNET_MQ_set_handlers_closure (struct GNUNET_MQ_Handle *mq,
606                                 void *handlers_cls);
607
608
609 /**
610  * Call a callback once the envelope has been sent, that is,
611  * sending it can not be canceled anymore.
612  * There can be only one notify sent callback per envelope.
613  *
614  * @param ev message to call the notify callback for
615  * @param cb the notify callback
616  * @param cls closure for the callback
617  */
618 void
619 GNUNET_MQ_notify_sent (struct GNUNET_MQ_Envelope *ev,
620                        GNUNET_MQ_NotifyCallback cb,
621                        void *cls);
622
623
624 /**
625  * Destroy the message queue.
626  *
627  * @param mq message queue to destroy
628  */
629 void
630 GNUNET_MQ_destroy (struct GNUNET_MQ_Handle *mq);
631
632
633 /**
634  * Call the message message handler that was registered
635  * for the type of the given message in the given message queue.
636  *
637  * This function is indended to be used for the implementation
638  * of message queues.
639  *
640  * @param mq message queue with the handlers
641  * @param mh message to dispatch
642  */
643 void
644 GNUNET_MQ_inject_message (struct GNUNET_MQ_Handle *mq,
645                           const struct GNUNET_MessageHeader *mh);
646
647
648 /**
649  * Call the error handler of a message queue with the given
650  * error code.  If there is no error handler, log a warning.
651  *
652  * This function is intended to be used for the implementation
653  * of message queues.
654  *
655  * @param mq message queue
656  * @param error the error type
657  */
658 void
659 GNUNET_MQ_inject_error (struct GNUNET_MQ_Handle *mq,
660                         enum GNUNET_MQ_Error error);
661
662
663 /**
664  * Call the send implementation for the next queued message, if any.
665  * Only useful for implementing message queues, results in undefined
666  * behavior if not used carefully.
667  *
668  * @param mq message queue to send the next message with
669  */
670 void
671 GNUNET_MQ_impl_send_continue (struct GNUNET_MQ_Handle *mq);
672
673
674 /**
675  * Get the message that should currently be sent.  The returned
676  * message is only valid until #GNUNET_MQ_impl_send_continue is
677  * called.  Fails if there is no current message.  Only useful for
678  * implementing message queues, results in undefined behavior if not
679  * used carefully.
680  *
681  * @param mq message queue with the current message, only valid
682  *        until #GNUNET_MQ_impl_send_continue() is called
683  * @return message to send, never NULL
684  */
685 const struct GNUNET_MessageHeader *
686 GNUNET_MQ_impl_current (struct GNUNET_MQ_Handle *mq);
687
688
689 /**
690  * Get the implementation state associated with the
691  * message queue.
692  *
693  * While the GNUNET_MQ_Impl* callbacks receive the
694  * implementation state, continuations that are scheduled
695  * by the implementation function often only have one closure
696  * argument, with this function it is possible to get at the
697  * implementation state when only passing the `struct GNUNET_MQ_Handle`
698  * as closure.
699  *
700  * @param mq message queue with the current message
701  * @return message to send, never NULL
702  */
703 void *
704 GNUNET_MQ_impl_state (struct GNUNET_MQ_Handle *mq);
705
706
707 #endif
708
709 /** @} */ /* end of group mq */