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