4984df76c4e237d53010495e3f5f5110822db43a
[oweals/gnunet.git] / src / util / mq.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012-2017 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  * @file util/mq.c
24  * @brief general purpose request queue
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28
29 #define LOG(kind,...) GNUNET_log_from (kind, "util-mq",__VA_ARGS__)
30
31 //#if HAVE_EXECINFO_H
32 //#include "execinfo.h"
33
34 ///**
35 // * Use lsof to generate file descriptor reports on select error?
36 // * (turn off for stable releases).
37 // */
38 //#define USE_LSOF GNUNET_NO
39
40 ///**
41 // * Obtain trace information for all scheduler calls that schedule tasks.
42 // */
43 //#define EXECINFO GNUNET_NO
44
45 ///**
46 // * Check each file descriptor before adding
47 // */
48 //#define DEBUG_FDS GNUNET_NO
49
50 ///**
51 // * Depth of the traces collected via EXECINFO.
52 // */
53 //#define MAX_TRACE_DEPTH 50
54 //#endif
55
56 struct GNUNET_MQ_Envelope
57 {
58   /**
59    * Messages are stored in a linked list.
60    * Each queue has its own list of envelopes.
61    */
62   struct GNUNET_MQ_Envelope *next;
63
64   /**
65    * Messages are stored in a linked list
66    * Each queue has its own list of envelopes.
67    */
68   struct GNUNET_MQ_Envelope *prev;
69
70   /**
71    * Actual allocated message header.
72    * The GNUNET_MQ_Envelope header is allocated at
73    * the end of the message.
74    */
75   struct GNUNET_MessageHeader *mh;
76
77   /**
78    * Queue the message is queued in, NULL if message is not queued.
79    */
80   struct GNUNET_MQ_Handle *parent_queue;
81
82   /**
83    * Called after the message was sent irrevocably.
84    */
85   GNUNET_SCHEDULER_TaskCallback sent_cb;
86
87   /**
88    * Closure for @e sent_cb
89    */
90   void *sent_cls;
91
92   /**
93    * Flags that were set for this envelope by
94    * #GNUNET_MQ_env_set_options().   Only valid if
95    * @e have_custom_options is set.
96    */
97   uint64_t flags;
98
99   /**
100    * Additional options buffer set for this envelope by
101    * #GNUNET_MQ_env_set_options().  Only valid if
102    * @e have_custom_options is set.
103    */
104   const void *extra;
105
106   /**
107    * Did the application call #GNUNET_MQ_env_set_options()?
108    */
109   int have_custom_options;
110 };
111
112
113 /**
114  * Handle to a message queue.
115  */
116 struct GNUNET_MQ_Handle
117 {
118   /**
119    * Handlers array, or NULL if the queue should not receive messages
120    */
121   struct GNUNET_MQ_MessageHandler *handlers;
122
123   /**
124    * Actual implementation of message sending,
125    * called when a message is added
126    */
127   GNUNET_MQ_SendImpl send_impl;
128
129   /**
130    * Implementation-dependent queue destruction function
131    */
132   GNUNET_MQ_DestroyImpl destroy_impl;
133
134   /**
135    * Implementation-dependent send cancel function
136    */
137   GNUNET_MQ_CancelImpl cancel_impl;
138
139   /**
140    * Implementation-specific state
141    */
142   void *impl_state;
143
144   /**
145    * Callback will be called when an error occurs.
146    */
147   GNUNET_MQ_ErrorHandler error_handler;
148
149   /**
150    * Closure for the error handler.
151    */
152   void *error_handler_cls;
153
154   /**
155    * Task to asynchronously run #impl_send_continue().
156    */
157   struct GNUNET_SCHEDULER_Task *send_task;
158
159   /**
160    * Linked list of messages pending to be sent
161    */
162   struct GNUNET_MQ_Envelope *envelope_head;
163
164   /**
165    * Linked list of messages pending to be sent
166    */
167   struct GNUNET_MQ_Envelope *envelope_tail;
168
169   /**
170    * Message that is currently scheduled to be
171    * sent. Not the head of the message queue, as the implementation
172    * needs to know if sending has been already scheduled or not.
173    */
174   struct GNUNET_MQ_Envelope *current_envelope;
175
176   /**
177    * Map of associations, lazily allocated
178    */
179   struct GNUNET_CONTAINER_MultiHashMap32 *assoc_map;
180
181   /**
182    * Functions to call on queue destruction; kept in a DLL.
183    */
184   struct GNUNET_MQ_DestroyNotificationHandle *dnh_head;
185
186   /**
187    * Functions to call on queue destruction; kept in a DLL.
188    */
189   struct GNUNET_MQ_DestroyNotificationHandle *dnh_tail;
190
191   /**
192    * Additional options buffer set for this queue by
193    * #GNUNET_MQ_set_options().  Default is 0.
194    */
195   const void *default_extra;
196
197   /**
198    * Flags that were set for this queue by
199    * #GNUNET_MQ_set_options().   Default is 0.
200    */
201   uint64_t default_flags;
202
203   /**
204    * Next id that should be used for the @e assoc_map,
205    * initialized lazily to a random value together with
206    * @e assoc_map
207    */
208   uint32_t assoc_id;
209
210   /**
211    * Number of entries we have in the envelope-DLL.
212    */
213   unsigned int queue_length;
214
215   /**
216    * #GNUNET_YES if GNUNET_MQ_impl_evacuate was called.
217    * FIXME: is this dead?
218    */
219   int evacuate_called;
220
221   /**
222    * #GNUNET_YES if GNUNET_MQ_impl_send_in_flight() was called.
223    */
224   int in_flight;
225 };
226
227
228 /**
229  * Call the message message handler that was registered
230  * for the type of the given message in the given message queue.
231  *
232  * This function is indended to be used for the implementation
233  * of message queues.
234  *
235  * @param mq message queue with the handlers
236  * @param mh message to dispatch
237  */
238 void
239 GNUNET_MQ_inject_message (struct GNUNET_MQ_Handle *mq,
240                           const struct GNUNET_MessageHeader *mh)
241 {
242   const struct GNUNET_MQ_MessageHandler *handler;
243   int handled = GNUNET_NO;
244   uint16_t msize = ntohs (mh->size);
245   uint16_t mtype = ntohs (mh->type);
246
247   LOG (GNUNET_ERROR_TYPE_DEBUG,
248        "Queue %p received message of type %u and size %u\n",
249        mq,
250        mtype,
251        msize);
252
253   if (NULL == mq->handlers)
254     goto done;
255   for (handler = mq->handlers; NULL != handler->cb; handler++)
256   {
257     if (handler->type == mtype)
258     {
259       handled = GNUNET_YES;
260       if ( (handler->expected_size > msize) ||
261            ( (handler->expected_size != msize) &&
262              (NULL == handler->mv) ) )
263       {
264         /* Too small, or not an exact size and
265            no 'mv' handler to check rest */
266         LOG (GNUNET_ERROR_TYPE_ERROR,
267              "Received malformed message of type %u\n",
268              (unsigned int) handler->type);
269         GNUNET_MQ_inject_error (mq,
270                                 GNUNET_MQ_ERROR_MALFORMED);
271         break;
272       }
273       if ( (NULL == handler->mv) ||
274            (GNUNET_OK ==
275             handler->mv (handler->cls, mh)) )
276       {
277         /* message well-formed, pass to handler */
278         handler->cb (handler->cls, mh);
279       }
280       else
281       {
282         /* Message rejected by check routine */
283         LOG (GNUNET_ERROR_TYPE_ERROR,
284              "Received malformed message of type %u\n",
285              (unsigned int) handler->type);
286         GNUNET_MQ_inject_error (mq,
287                                 GNUNET_MQ_ERROR_MALFORMED);
288       }
289       break;
290     }
291   }
292  done:
293   if (GNUNET_NO == handled)
294     LOG (GNUNET_ERROR_TYPE_INFO,
295          "No handler for message of type %u and size %u\n",
296          mtype, msize);
297 }
298
299
300 /**
301  * Call the error handler of a message queue with the given
302  * error code.  If there is no error handler, log a warning.
303  *
304  * This function is intended to be used by the implementation
305  * of message queues.
306  *
307  * @param mq message queue
308  * @param error the error type
309  */
310 void
311 GNUNET_MQ_inject_error (struct GNUNET_MQ_Handle *mq,
312                         enum GNUNET_MQ_Error error)
313 {
314   if (NULL == mq->error_handler)
315   {
316     LOG (GNUNET_ERROR_TYPE_WARNING,
317          "Got error %d, but no handler installed\n",
318          (int) error);
319     return;
320   }
321   mq->error_handler (mq->error_handler_cls,
322                      error);
323 }
324
325
326 /**
327  * Discard the message queue message, free all
328  * allocated resources. Must be called in the event
329  * that a message is created but should not actually be sent.
330  *
331  * @param mqm the message to discard
332  */
333 void
334 GNUNET_MQ_discard (struct GNUNET_MQ_Envelope *ev)
335 {
336   GNUNET_assert (NULL == ev->parent_queue);
337   GNUNET_free (ev);
338 }
339
340
341 /**
342  * Obtain the current length of the message queue.
343  *
344  * @param mq queue to inspect
345  * @return number of queued, non-transmitted messages
346  */
347 unsigned int
348 GNUNET_MQ_get_length (struct GNUNET_MQ_Handle *mq)
349 {
350   if (GNUNET_YES != mq->in_flight)
351   {
352     return mq->queue_length;
353   }
354   return mq->queue_length - 1;
355 }
356
357
358 /**
359  * Send a message with the given message queue.
360  * May only be called once per message.
361  *
362  * @param mq message queue
363  * @param ev the envelope with the message to send.
364  */
365 void
366 GNUNET_MQ_send (struct GNUNET_MQ_Handle *mq,
367                 struct GNUNET_MQ_Envelope *ev)
368 {
369   GNUNET_assert (NULL != mq);
370   GNUNET_assert (NULL == ev->parent_queue);
371
372   mq->queue_length++;
373   GNUNET_break (mq->queue_length < 10000); /* This would seem like a bug... */
374   ev->parent_queue = mq;
375   /* is the implementation busy? queue it! */
376   if ( (NULL != mq->current_envelope) ||
377        (NULL != mq->send_task) )
378   {
379     GNUNET_CONTAINER_DLL_insert_tail (mq->envelope_head,
380                                       mq->envelope_tail,
381                                       ev);
382     return;
383   }
384   GNUNET_assert (NULL == mq->envelope_head);
385   mq->current_envelope = ev;
386
387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
388               "mq: sending message of type %u, queue empty (MQ: %p)\n",
389               ntohs(ev->mh->type),
390               mq);
391
392   mq->send_impl (mq,
393                  ev->mh,
394                  mq->impl_state);
395 }
396
397
398 /**
399  * Remove the first envelope that has not yet been sent from the message
400  * queue and return it.
401  *
402  * @param mq queue to remove envelope from
403  * @return NULL if queue is empty (or has no envelope that is not under transmission)
404  */
405 struct GNUNET_MQ_Envelope *
406 GNUNET_MQ_unsent_head (struct GNUNET_MQ_Handle *mq)
407 {
408   struct GNUNET_MQ_Envelope *env;
409
410   env = mq->envelope_head;
411   GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
412                                mq->envelope_tail,
413                                env);
414   mq->queue_length--;
415   env->parent_queue = NULL;
416   return env;
417 }
418
419
420 /**
421  * Function to copy an envelope.  The envelope must not yet
422  * be in any queue or have any options or callbacks set.
423  *
424  * @param env envelope to copy
425  * @return copy of @a env
426  */
427 struct GNUNET_MQ_Envelope *
428 GNUNET_MQ_env_copy (struct GNUNET_MQ_Envelope *env)
429 {
430   GNUNET_assert (NULL == env->next);
431   GNUNET_assert (NULL == env->parent_queue);
432   GNUNET_assert (NULL == env->sent_cb);
433   GNUNET_assert (GNUNET_NO == env->have_custom_options);
434   return GNUNET_MQ_msg_copy (env->mh);
435 }
436
437
438 /**
439  * Send a copy of a message with the given message queue.
440  * Can be called repeatedly on the same envelope.
441  *
442  * @param mq message queue
443  * @param ev the envelope with the message to send.
444  */
445 void
446 GNUNET_MQ_send_copy (struct GNUNET_MQ_Handle *mq,
447                      const struct GNUNET_MQ_Envelope *ev)
448 {
449   struct GNUNET_MQ_Envelope *env;
450   uint16_t msize;
451
452   msize = ntohs (ev->mh->size);
453   env = GNUNET_malloc (sizeof (struct GNUNET_MQ_Envelope) +
454                        msize);
455   env->mh = (struct GNUNET_MessageHeader *) &env[1];
456   env->sent_cb = ev->sent_cb;
457   env->sent_cls = ev->sent_cls;
458   GNUNET_memcpy (&env[1],
459           ev->mh,
460           msize);
461   GNUNET_MQ_send (mq,
462                   env);
463 }
464
465
466 /**
467  * Task run to call the send implementation for the next queued
468  * message, if any.  Only useful for implementing message queues,
469  * results in undefined behavior if not used carefully.
470  *
471  * @param cls message queue to send the next message with
472  */
473 static void
474 impl_send_continue (void *cls)
475 {
476   struct GNUNET_MQ_Handle *mq = cls;
477
478   mq->send_task = NULL;
479   /* call is only valid if we're actually currently sending
480    * a message */
481   if (NULL == mq->envelope_head)
482     return;
483   mq->current_envelope = mq->envelope_head;
484   GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
485                                mq->envelope_tail,
486                                mq->current_envelope);
487
488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
489               "mq: sending message of type %u from queue\n",
490               ntohs(mq->current_envelope->mh->type));
491
492   mq->send_impl (mq,
493                  mq->current_envelope->mh,
494                  mq->impl_state);
495 }
496
497
498 /**
499  * Call the send implementation for the next queued message, if any.
500  * Only useful for implementing message queues, results in undefined
501  * behavior if not used carefully.
502  *
503  * @param mq message queue to send the next message with
504  */
505 void
506 GNUNET_MQ_impl_send_continue (struct GNUNET_MQ_Handle *mq)
507 {
508   struct GNUNET_MQ_Envelope *current_envelope;
509   GNUNET_SCHEDULER_TaskCallback cb;
510
511   GNUNET_assert (0 < mq->queue_length);
512   mq->queue_length--;
513   mq->in_flight = GNUNET_NO;
514   current_envelope = mq->current_envelope;
515   current_envelope->parent_queue = NULL;
516   mq->current_envelope = NULL;
517   GNUNET_assert (NULL == mq->send_task);
518   mq->send_task = GNUNET_SCHEDULER_add_now (&impl_send_continue,
519                                             mq);
520   if (NULL != (cb = current_envelope->sent_cb))
521   {
522     current_envelope->sent_cb = NULL;
523     cb (current_envelope->sent_cls);
524   }
525   GNUNET_free (current_envelope);
526 }
527
528
529 /**
530  * Call the send notification for the current message, but do not
531  * try to send the next message until #GNUNET_MQ_impl_send_continue
532  * is called.
533  *
534  * Only useful for implementing message queues, results in undefined
535  * behavior if not used carefully.
536  *
537  * @param mq message queue to send the next message with
538  */
539 void
540 GNUNET_MQ_impl_send_in_flight (struct GNUNET_MQ_Handle *mq)
541 {
542   struct GNUNET_MQ_Envelope *current_envelope;
543   GNUNET_SCHEDULER_TaskCallback cb;
544
545   mq->in_flight = GNUNET_YES;
546   /* call is only valid if we're actually currently sending
547    * a message */
548   current_envelope = mq->current_envelope;
549   GNUNET_assert (NULL != current_envelope);
550   /* can't call cancel from now on anymore */
551   current_envelope->parent_queue = NULL;
552   if (NULL != (cb = current_envelope->sent_cb))
553   {
554     current_envelope->sent_cb = NULL;
555     cb (current_envelope->sent_cls);
556   }
557 }
558
559
560 /**
561  * Create a message queue for the specified handlers.
562  *
563  * @param send function the implements sending messages
564  * @param destroy function that implements destroying the queue
565  * @param cancel function that implements canceling a message
566  * @param impl_state for the queue, passed to 'send' and 'destroy'
567  * @param handlers array of message handlers
568  * @param error_handler handler for read and write errors
569  * @param error_handler_cls closure for @a error_handler
570  * @return a new message queue
571  */
572 struct GNUNET_MQ_Handle *
573 GNUNET_MQ_queue_for_callbacks (GNUNET_MQ_SendImpl send,
574                                GNUNET_MQ_DestroyImpl destroy,
575                                GNUNET_MQ_CancelImpl cancel,
576                                void *impl_state,
577                                const struct GNUNET_MQ_MessageHandler *handlers,
578                                GNUNET_MQ_ErrorHandler error_handler,
579                                void *error_handler_cls)
580 {
581   struct GNUNET_MQ_Handle *mq;
582
583   mq = GNUNET_new (struct GNUNET_MQ_Handle);
584   mq->send_impl = send;
585   mq->destroy_impl = destroy;
586   mq->cancel_impl = cancel;
587   mq->handlers = GNUNET_MQ_copy_handlers (handlers);
588   mq->error_handler = error_handler;
589   mq->error_handler_cls = error_handler_cls;
590   mq->impl_state = impl_state;
591
592   return mq;
593 }
594
595
596 /**
597  * Change the closure argument in all of the `handlers` of the
598  * @a mq.
599  *
600  * @param mq to modify
601  * @param handlers_cls new closure to use
602  */
603 void
604 GNUNET_MQ_set_handlers_closure (struct GNUNET_MQ_Handle *mq,
605                                 void *handlers_cls)
606 {
607   unsigned int i;
608
609   if (NULL == mq->handlers)
610     return;
611   for (i=0;NULL != mq->handlers[i].cb; i++)
612     mq->handlers[i].cls = handlers_cls;
613 }
614
615
616 /**
617  * Get the message that should currently be sent.
618  * Fails if there is no current message.
619  * Only useful for implementing message queues,
620  * results in undefined behavior if not used carefully.
621  *
622  * @param mq message queue with the current message
623  * @return message to send, never NULL
624  */
625 const struct GNUNET_MessageHeader *
626 GNUNET_MQ_impl_current (struct GNUNET_MQ_Handle *mq)
627 {
628   GNUNET_assert (NULL != mq->current_envelope);
629   GNUNET_assert (NULL != mq->current_envelope->mh);
630   return mq->current_envelope->mh;
631 }
632
633
634 /**
635  * Get the implementation state associated with the
636  * message queue.
637  *
638  * While the GNUNET_MQ_Impl* callbacks receive the
639  * implementation state, continuations that are scheduled
640  * by the implementation function often only have one closure
641  * argument, with this function it is possible to get at the
642  * implementation state when only passing the GNUNET_MQ_Handle
643  * as closure.
644  *
645  * @param mq message queue with the current message
646  * @return message to send, never NULL
647  */
648 void *
649 GNUNET_MQ_impl_state (struct GNUNET_MQ_Handle *mq)
650 {
651   return mq->impl_state;
652 }
653
654
655 struct GNUNET_MQ_Envelope *
656 GNUNET_MQ_msg_ (struct GNUNET_MessageHeader **mhp,
657                 uint16_t size,
658                 uint16_t type)
659 {
660   struct GNUNET_MQ_Envelope *ev;
661
662   ev = GNUNET_malloc (size + sizeof (struct GNUNET_MQ_Envelope));
663   ev->mh = (struct GNUNET_MessageHeader *) &ev[1];
664   ev->mh->size = htons (size);
665   ev->mh->type = htons (type);
666   if (NULL != mhp)
667     *mhp = ev->mh;
668   return ev;
669 }
670
671
672 /**
673  * Create a new envelope by copying an existing message.
674  *
675  * @param hdr header of the message to copy
676  * @return envelope containing @a hdr
677  */
678 struct GNUNET_MQ_Envelope *
679 GNUNET_MQ_msg_copy (const struct GNUNET_MessageHeader *hdr)
680 {
681   struct GNUNET_MQ_Envelope *mqm;
682   uint16_t size = ntohs (hdr->size);
683
684   mqm = GNUNET_malloc (sizeof (*mqm) + size);
685   mqm->mh = (struct GNUNET_MessageHeader *) &mqm[1];
686   GNUNET_memcpy (mqm->mh,
687           hdr,
688           size);
689   return mqm;
690 }
691
692
693 /**
694  * Implementation of the #GNUNET_MQ_msg_nested_mh macro.
695  *
696  * @param mhp pointer to the message header pointer that will be changed to allocate at
697  *        the newly allocated space for the message.
698  * @param base_size size of the data before the nested message
699  * @param type type of the message in the envelope
700  * @param nested_mh the message to append to the message after base_size
701  */
702 struct GNUNET_MQ_Envelope *
703 GNUNET_MQ_msg_nested_mh_ (struct GNUNET_MessageHeader **mhp,
704                           uint16_t base_size,
705                           uint16_t type,
706                           const struct GNUNET_MessageHeader *nested_mh)
707 {
708   struct GNUNET_MQ_Envelope *mqm;
709   uint16_t size;
710
711   if (NULL == nested_mh)
712     return GNUNET_MQ_msg_ (mhp, base_size, type);
713
714   size = base_size + ntohs (nested_mh->size);
715
716   /* check for uint16_t overflow */
717   if (size < base_size)
718     return NULL;
719
720   mqm = GNUNET_MQ_msg_ (mhp, size, type);
721   GNUNET_memcpy ((char *) mqm->mh + base_size,
722                  nested_mh,
723                  ntohs (nested_mh->size));
724
725   return mqm;
726 }
727
728
729 /**
730  * Associate the assoc_data in mq with a unique request id.
731  *
732  * @param mq message queue, id will be unique for the queue
733  * @param assoc_data to associate
734  */
735 uint32_t
736 GNUNET_MQ_assoc_add (struct GNUNET_MQ_Handle *mq,
737                      void *assoc_data)
738 {
739   uint32_t id;
740
741   if (NULL == mq->assoc_map)
742   {
743     mq->assoc_map = GNUNET_CONTAINER_multihashmap32_create (8);
744     mq->assoc_id = 1;
745   }
746   id = mq->assoc_id++;
747   GNUNET_assert (GNUNET_OK ==
748                  GNUNET_CONTAINER_multihashmap32_put (mq->assoc_map,
749                                                       id,
750                                                       assoc_data,
751                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
752   return id;
753 }
754
755
756 /**
757  * Get the data associated with a @a request_id in a queue
758  *
759  * @param mq the message queue with the association
760  * @param request_id the request id we are interested in
761  * @return the associated data
762  */
763 void *
764 GNUNET_MQ_assoc_get (struct GNUNET_MQ_Handle *mq,
765                      uint32_t request_id)
766 {
767   if (NULL == mq->assoc_map)
768     return NULL;
769   return GNUNET_CONTAINER_multihashmap32_get (mq->assoc_map,
770                                               request_id);
771 }
772
773
774 /**
775  * Remove the association for a @a request_id
776  *
777  * @param mq the message queue with the association
778  * @param request_id the request id we want to remove
779  * @return the associated data
780  */
781 void *
782 GNUNET_MQ_assoc_remove (struct GNUNET_MQ_Handle *mq,
783                         uint32_t request_id)
784 {
785   void *val;
786
787   if (NULL == mq->assoc_map)
788     return NULL;
789   val = GNUNET_CONTAINER_multihashmap32_get (mq->assoc_map,
790                                              request_id);
791   GNUNET_CONTAINER_multihashmap32_remove_all (mq->assoc_map,
792                                               request_id);
793   return val;
794 }
795
796
797 /**
798  * Call a callback once the envelope has been sent, that is,
799  * sending it can not be canceled anymore.
800  * There can be only one notify sent callback per envelope.
801  *
802  * @param ev message to call the notify callback for
803  * @param cb the notify callback
804  * @param cb_cls closure for the callback
805  */
806 void
807 GNUNET_MQ_notify_sent (struct GNUNET_MQ_Envelope *ev,
808                        GNUNET_SCHEDULER_TaskCallback cb,
809                        void *cb_cls)
810 {
811   GNUNET_assert (NULL == ev->sent_cb);
812   ev->sent_cb = cb;
813   ev->sent_cls = cb_cls;
814 }
815
816
817 /**
818  * Handle we return for callbacks registered to be
819  * notified when #GNUNET_MQ_destroy() is called on a queue.
820  */
821 struct GNUNET_MQ_DestroyNotificationHandle
822 {
823   /**
824    * Kept in a DLL.
825    */
826   struct GNUNET_MQ_DestroyNotificationHandle *prev;
827
828   /**
829    * Kept in a DLL.
830    */
831   struct GNUNET_MQ_DestroyNotificationHandle *next;
832
833   /**
834    * Queue to notify about.
835    */
836   struct GNUNET_MQ_Handle *mq;
837
838   /**
839    * Function to call.
840    */
841   GNUNET_SCHEDULER_TaskCallback cb;
842
843   /**
844    * Closure for @e cb.
845    */
846   void *cb_cls;
847 };
848
849
850 /**
851  * Destroy the message queue.
852  *
853  * @param mq message queue to destroy
854  */
855 void
856 GNUNET_MQ_destroy (struct GNUNET_MQ_Handle *mq)
857 {
858   struct GNUNET_MQ_DestroyNotificationHandle *dnh;
859
860   if (NULL != mq->destroy_impl)
861   {
862     mq->destroy_impl (mq, mq->impl_state);
863   }
864   if (NULL != mq->send_task)
865   {
866     GNUNET_SCHEDULER_cancel (mq->send_task);
867     mq->send_task = NULL;
868   }
869   while (NULL != mq->envelope_head)
870   {
871     struct GNUNET_MQ_Envelope *ev;
872
873     ev = mq->envelope_head;
874     ev->parent_queue = NULL;
875     GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
876                                  mq->envelope_tail,
877                                  ev);
878     GNUNET_assert (0 < mq->queue_length);
879     mq->queue_length--;
880     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
881                 "MQ destroy drops message of type %u\n",
882                 ntohs (ev->mh->type));
883     GNUNET_MQ_discard (ev);
884   }
885   if (NULL != mq->current_envelope)
886   {
887     /* we can only discard envelopes that
888      * are not queued! */
889     mq->current_envelope->parent_queue = NULL;
890     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
891                 "MQ destroy drops current message of type %u\n",
892                 ntohs (mq->current_envelope->mh->type));
893 //#if EXECINFO
894 //  void *backtrace_array[MAX_TRACE_DEPTH];
895 //  int num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
896 //    char **backtrace_strings =
897 //        backtrace_symbols (backtrace_array,
898 //         t->num_backtrace_strings);
899 //    for (unsigned int i = 0; i < num_backtrace_strings; i++)
900 //      LOG (GNUNET_ERROR_TYPE_DEBUG,
901 //     "client drop trace %u: %s\n",
902 //     i,
903 //     backtrace_strings[i]);
904 //#endif
905     GNUNET_MQ_discard (mq->current_envelope);
906     mq->current_envelope = NULL;
907     GNUNET_assert (0 < mq->queue_length);
908     mq->queue_length--;
909   }
910   GNUNET_assert (0 == mq->queue_length);
911   while (NULL != (dnh = mq->dnh_head))
912   {
913     dnh->cb (dnh->cb_cls);
914     GNUNET_MQ_destroy_notify_cancel (dnh);
915   }
916   if (NULL != mq->assoc_map)
917   {
918     GNUNET_CONTAINER_multihashmap32_destroy (mq->assoc_map);
919     mq->assoc_map = NULL;
920   }
921   GNUNET_free_non_null (mq->handlers);
922   GNUNET_free (mq);
923 }
924
925
926 const struct GNUNET_MessageHeader *
927 GNUNET_MQ_extract_nested_mh_ (const struct GNUNET_MessageHeader *mh,
928                               uint16_t base_size)
929 {
930   uint16_t whole_size;
931   uint16_t nested_size;
932   const struct GNUNET_MessageHeader *nested_msg;
933
934   whole_size = ntohs (mh->size);
935   GNUNET_assert (whole_size >= base_size);
936   nested_size = whole_size - base_size;
937   if (0 == nested_size)
938     return NULL;
939   if (nested_size < sizeof (struct GNUNET_MessageHeader))
940   {
941     GNUNET_break_op (0);
942     return NULL;
943   }
944   nested_msg = (const struct GNUNET_MessageHeader *) ((char *) mh + base_size);
945   if (ntohs (nested_msg->size) != nested_size)
946   {
947     GNUNET_break_op (0);
948     return NULL;
949   }
950   return nested_msg;
951 }
952
953
954 /**
955  * Cancel sending the message. Message must have been sent with
956  * #GNUNET_MQ_send before.  May not be called after the notify sent
957  * callback has been called
958  *
959  * @param ev queued envelope to cancel
960  */
961 void
962 GNUNET_MQ_send_cancel (struct GNUNET_MQ_Envelope *ev)
963 {
964   struct GNUNET_MQ_Handle *mq = ev->parent_queue;
965
966   GNUNET_assert (NULL != mq);
967   GNUNET_assert (NULL != mq->cancel_impl);
968
969   mq->evacuate_called = GNUNET_NO;
970
971   if (mq->current_envelope == ev)
972   {
973     /* complex case, we already started with transmitting
974        the message using the callbacks. */
975     GNUNET_assert (0 < mq->queue_length);
976     mq->queue_length--;
977     mq->cancel_impl (mq,
978                      mq->impl_state);
979     /* continue sending the next message, if any */
980     mq->current_envelope = mq->envelope_head;
981     if (NULL != mq->current_envelope)
982     {
983       GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
984                                    mq->envelope_tail,
985                                    mq->current_envelope);
986
987       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
988                   "mq: sending canceled message of type %u queue\n",
989                   ntohs(ev->mh->type));
990
991       mq->send_impl (mq,
992                      mq->current_envelope->mh,
993                      mq->impl_state);
994     }
995   }
996   else
997   {
998     /* simple case, message is still waiting in the queue */
999     GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
1000                                  mq->envelope_tail,
1001                                  ev);
1002     GNUNET_assert (0 < mq->queue_length);
1003     mq->queue_length--;
1004   }
1005
1006   if (GNUNET_YES != mq->evacuate_called)
1007   {
1008     ev->parent_queue = NULL;
1009     ev->mh = NULL;
1010     /* also frees ev */
1011     GNUNET_free (ev);
1012   }
1013 }
1014
1015
1016 /**
1017  * Function to obtain the current envelope
1018  * from within #GNUNET_MQ_SendImpl implementations.
1019  *
1020  * @param mq message queue to interrogate
1021  * @return the current envelope
1022  */
1023 struct GNUNET_MQ_Envelope *
1024 GNUNET_MQ_get_current_envelope (struct GNUNET_MQ_Handle *mq)
1025 {
1026   return mq->current_envelope;
1027 }
1028
1029
1030 /**
1031  * Function to obtain the last envelope in the queue.
1032  *
1033  * @param mq message queue to interrogate
1034  * @return the last envelope in the queue
1035  */
1036 struct GNUNET_MQ_Envelope *
1037 GNUNET_MQ_get_last_envelope (struct GNUNET_MQ_Handle *mq)
1038 {
1039   if (NULL != mq->envelope_tail)
1040     return mq->envelope_tail;
1041
1042   return mq->current_envelope;
1043 }
1044
1045
1046 /**
1047  * Set application-specific options for this envelope.
1048  * Overrides the options set for the queue with
1049  * #GNUNET_MQ_set_options() for this message only.
1050  *
1051  * @param env message to set options for
1052  * @param flags flags to use (meaning is queue-specific)
1053  * @param extra additional buffer for further data (also queue-specific)
1054  */
1055 void
1056 GNUNET_MQ_env_set_options (struct GNUNET_MQ_Envelope *env,
1057                            uint64_t flags,
1058                            const void *extra)
1059 {
1060   env->flags = flags;
1061   env->extra = extra;
1062   env->have_custom_options = GNUNET_YES;
1063 }
1064
1065
1066 /**
1067  * Get application-specific options for this envelope.
1068  *
1069  * @param env message to set options for
1070  * @param[out] flags set to flags to use (meaning is queue-specific)
1071  * @return extra additional buffer for further data (also queue-specific)
1072  */
1073 const void *
1074 GNUNET_MQ_env_get_options (struct GNUNET_MQ_Envelope *env,
1075                            uint64_t *flags)
1076 {
1077   struct GNUNET_MQ_Handle *mq = env->parent_queue;
1078
1079   if (GNUNET_YES == env->have_custom_options)
1080   {
1081     *flags = env->flags;
1082     return env->extra;
1083   }
1084   if (NULL == mq)
1085   {
1086     *flags = 0;
1087     return NULL;
1088   }
1089   *flags = mq->default_flags;
1090   return mq->default_extra;
1091 }
1092
1093
1094 /**
1095  * Set application-specific options for this queue.
1096  *
1097  * @param mq message queue to set options for
1098  * @param flags flags to use (meaning is queue-specific)
1099  * @param extra additional buffer for further data (also queue-specific)
1100  */
1101 void
1102 GNUNET_MQ_set_options (struct GNUNET_MQ_Handle *mq,
1103                        uint64_t flags,
1104                        const void *extra)
1105 {
1106   mq->default_flags = flags;
1107   mq->default_extra = extra;
1108 }
1109
1110
1111 /**
1112  * Register function to be called whenever @a mq is being
1113  * destroyed.
1114  *
1115  * @param mq message queue to watch
1116  * @param cb function to call on @a mq destruction
1117  * @param cb_cls closure for @a cb
1118  * @return handle for #GNUNET_MQ_destroy_notify_cancel().
1119  */
1120 struct GNUNET_MQ_DestroyNotificationHandle *
1121 GNUNET_MQ_destroy_notify (struct GNUNET_MQ_Handle *mq,
1122                           GNUNET_SCHEDULER_TaskCallback cb,
1123                           void *cb_cls)
1124 {
1125   struct GNUNET_MQ_DestroyNotificationHandle *dnh;
1126
1127   dnh = GNUNET_new (struct GNUNET_MQ_DestroyNotificationHandle);
1128   dnh->mq = mq;
1129   dnh->cb = cb;
1130   dnh->cb_cls = cb_cls;
1131   GNUNET_CONTAINER_DLL_insert (mq->dnh_head,
1132                                mq->dnh_tail,
1133                                dnh);
1134   return dnh;
1135 }
1136
1137
1138 /**
1139  * Cancel registration from #GNUNET_MQ_destroy_notify().
1140  *
1141  * @param dnh handle for registration to cancel
1142  */
1143 void
1144 GNUNET_MQ_destroy_notify_cancel (struct GNUNET_MQ_DestroyNotificationHandle *dnh)
1145 {
1146   struct GNUNET_MQ_Handle *mq = dnh->mq;
1147
1148   GNUNET_CONTAINER_DLL_remove (mq->dnh_head,
1149                                mq->dnh_tail,
1150                                dnh);
1151   GNUNET_free (dnh);
1152 }
1153
1154
1155 /**
1156  * Insert @a env into the envelope DLL starting at @a env_head
1157  * Note that @a env must not be in any MQ while this function
1158  * is used with DLLs defined outside of the MQ module.  This
1159  * is just in case some application needs to also manage a
1160  * FIFO of envelopes independent of MQ itself and wants to
1161  * re-use the pointers internal to @a env.  Use with caution.
1162  *
1163  * @param[in|out] env_head of envelope DLL
1164  * @param[in|out] env_tail tail of envelope DLL
1165  * @param[in|out] env element to insert at the tail
1166  */
1167 void
1168 GNUNET_MQ_dll_insert_tail (struct GNUNET_MQ_Envelope **env_head,
1169                            struct GNUNET_MQ_Envelope **env_tail,
1170                            struct GNUNET_MQ_Envelope *env)
1171 {
1172   GNUNET_CONTAINER_DLL_insert_tail (*env_head,
1173                                     *env_tail,
1174                                     env);
1175 }
1176
1177
1178 /**
1179  * Remove @a env from the envelope DLL starting at @a env_head.
1180  * Note that @a env must not be in any MQ while this function
1181  * is used with DLLs defined outside of the MQ module. This
1182  * is just in case some application needs to also manage a
1183  * FIFO of envelopes independent of MQ itself and wants to
1184  * re-use the pointers internal to @a env.  Use with caution.
1185  *
1186  * @param[in|out] env_head of envelope DLL
1187  * @param[in|out] env_tail tail of envelope DLL
1188  * @param[in|out] env element to remove from the DLL
1189  */
1190 void
1191 GNUNET_MQ_dll_remove (struct GNUNET_MQ_Envelope **env_head,
1192                       struct GNUNET_MQ_Envelope **env_tail,
1193                       struct GNUNET_MQ_Envelope *env)
1194 {
1195   GNUNET_CONTAINER_DLL_remove (*env_head,
1196                                *env_tail,
1197                                env);
1198 }
1199
1200
1201 /**
1202  * Copy an array of handlers.
1203  *
1204  * Useful if the array has been delared in local memory and needs to be
1205  * persisted for future use.
1206  *
1207  * @param handlers Array of handlers to be copied. Can be NULL (nothing done).
1208  * @return A newly allocated array of handlers.
1209  *         Needs to be freed with #GNUNET_free.
1210  */
1211 struct GNUNET_MQ_MessageHandler *
1212 GNUNET_MQ_copy_handlers (const struct GNUNET_MQ_MessageHandler *handlers)
1213 {
1214   struct GNUNET_MQ_MessageHandler *copy;
1215   unsigned int count;
1216
1217   if (NULL == handlers)
1218     return NULL;
1219
1220   count = GNUNET_MQ_count_handlers (handlers);
1221   copy = GNUNET_new_array (count + 1,
1222                            struct GNUNET_MQ_MessageHandler);
1223   GNUNET_memcpy (copy,
1224                  handlers,
1225                  count * sizeof (struct GNUNET_MQ_MessageHandler));
1226   return copy;
1227 }
1228
1229
1230 /**
1231  * Count the handlers in a handler array.
1232  *
1233  * @param handlers Array of handlers to be counted.
1234  * @return The number of handlers in the array.
1235  */
1236 unsigned int
1237 GNUNET_MQ_count_handlers (const struct GNUNET_MQ_MessageHandler *handlers)
1238 {
1239   unsigned int i;
1240
1241   if (NULL == handlers)
1242     return 0;
1243
1244   for (i=0; NULL != handlers[i].cb; i++) ;
1245
1246   return i;
1247 }
1248
1249
1250
1251 /* end of mq.c */