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