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