eliminate DHT PUT OK message by using MQ feature of calling continuation when transmi...
[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   LOG (GNUNET_ERROR_TYPE_DEBUG,
362        "sending message of type %u, queue empty (MQ: %p)\n",
363        ntohs(ev->mh->type),
364        mq);
365
366   mq->send_impl (mq,
367                  ev->mh,
368                  mq->impl_state);
369 }
370
371
372 /**
373  * Remove the first envelope that has not yet been sent from the message
374  * queue and return it.
375  *
376  * @param mq queue to remove envelope from
377  * @return NULL if queue is empty (or has no envelope that is not under transmission)
378  */
379 struct GNUNET_MQ_Envelope *
380 GNUNET_MQ_unsent_head (struct GNUNET_MQ_Handle *mq)
381 {
382   struct GNUNET_MQ_Envelope *env;
383
384   env = mq->envelope_head;
385   GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
386                                mq->envelope_tail,
387                                env);
388   mq->queue_length--;
389   env->parent_queue = NULL;
390   return env;
391 }
392
393
394 /**
395  * Function to copy an envelope.  The envelope must not yet
396  * be in any queue or have any options or callbacks set.
397  *
398  * @param env envelope to copy
399  * @return copy of @a env
400  */
401 struct GNUNET_MQ_Envelope *
402 GNUNET_MQ_env_copy (struct GNUNET_MQ_Envelope *env)
403 {
404   GNUNET_assert (NULL == env->next);
405   GNUNET_assert (NULL == env->parent_queue);
406   GNUNET_assert (NULL == env->sent_cb);
407   GNUNET_assert (GNUNET_NO == env->have_custom_options);
408   return GNUNET_MQ_msg_copy (env->mh);
409 }
410
411
412 /**
413  * Send a copy of a message with the given message queue.
414  * Can be called repeatedly on the same envelope.
415  *
416  * @param mq message queue
417  * @param ev the envelope with the message to send.
418  */
419 void
420 GNUNET_MQ_send_copy (struct GNUNET_MQ_Handle *mq,
421                      const struct GNUNET_MQ_Envelope *ev)
422 {
423   struct GNUNET_MQ_Envelope *env;
424   uint16_t msize;
425
426   msize = ntohs (ev->mh->size);
427   env = GNUNET_malloc (sizeof (struct GNUNET_MQ_Envelope) +
428                        msize);
429   env->mh = (struct GNUNET_MessageHeader *) &env[1];
430   env->sent_cb = ev->sent_cb;
431   env->sent_cls = ev->sent_cls;
432   GNUNET_memcpy (&env[1],
433           ev->mh,
434           msize);
435   GNUNET_MQ_send (mq,
436                   env);
437 }
438
439
440 /**
441  * Task run to call the send implementation for the next queued
442  * message, if any.  Only useful for implementing message queues,
443  * results in undefined behavior if not used carefully.
444  *
445  * @param cls message queue to send the next message with
446  */
447 static void
448 impl_send_continue (void *cls)
449 {
450   struct GNUNET_MQ_Handle *mq = cls;
451
452   mq->send_task = NULL;
453   /* call is only valid if we're actually currently sending
454    * a message */
455   if (NULL == mq->envelope_head)
456     return;
457   mq->current_envelope = mq->envelope_head;
458   GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
459                                mq->envelope_tail,
460                                mq->current_envelope);
461
462   LOG (GNUNET_ERROR_TYPE_DEBUG,
463        "sending message of type %u from queue\n",
464        ntohs(mq->current_envelope->mh->type));
465
466   mq->send_impl (mq,
467                  mq->current_envelope->mh,
468                  mq->impl_state);
469 }
470
471
472 /**
473  * Call the send implementation for the next queued message, if any.
474  * Only useful for implementing message queues, results in undefined
475  * behavior if not used carefully.
476  *
477  * @param mq message queue to send the next message with
478  */
479 void
480 GNUNET_MQ_impl_send_continue (struct GNUNET_MQ_Handle *mq)
481 {
482   struct GNUNET_MQ_Envelope *current_envelope;
483   GNUNET_SCHEDULER_TaskCallback cb;
484
485   GNUNET_assert (0 < mq->queue_length);
486   mq->queue_length--;
487   mq->in_flight = GNUNET_NO;
488   current_envelope = mq->current_envelope;
489   current_envelope->parent_queue = NULL;
490   mq->current_envelope = NULL;
491   GNUNET_assert (NULL == mq->send_task);
492   mq->send_task = GNUNET_SCHEDULER_add_now (&impl_send_continue,
493                                             mq);
494   if (NULL != (cb = current_envelope->sent_cb))
495   {
496     current_envelope->sent_cb = NULL;
497     cb (current_envelope->sent_cls);
498   }
499   GNUNET_free (current_envelope);
500 }
501
502
503 /**
504  * Call the send notification for the current message, but do not
505  * try to send the next message until #GNUNET_MQ_impl_send_continue
506  * is called.
507  *
508  * Only useful for implementing message queues, results in undefined
509  * behavior if not used carefully.
510  *
511  * @param mq message queue to send the next message with
512  */
513 void
514 GNUNET_MQ_impl_send_in_flight (struct GNUNET_MQ_Handle *mq)
515 {
516   struct GNUNET_MQ_Envelope *current_envelope;
517   GNUNET_SCHEDULER_TaskCallback cb;
518
519   mq->in_flight = GNUNET_YES;
520   /* call is only valid if we're actually currently sending
521    * a message */
522   current_envelope = mq->current_envelope;
523   GNUNET_assert (NULL != current_envelope);
524   /* can't call cancel from now on anymore */
525   current_envelope->parent_queue = NULL;
526   if (NULL != (cb = current_envelope->sent_cb))
527   {
528     current_envelope->sent_cb = NULL;
529     cb (current_envelope->sent_cls);
530   }
531 }
532
533
534 /**
535  * Create a message queue for the specified handlers.
536  *
537  * @param send function the implements sending messages
538  * @param destroy function that implements destroying the queue
539  * @param cancel function that implements canceling a message
540  * @param impl_state for the queue, passed to 'send' and 'destroy'
541  * @param handlers array of message handlers
542  * @param error_handler handler for read and write errors
543  * @param error_handler_cls closure for @a error_handler
544  * @return a new message queue
545  */
546 struct GNUNET_MQ_Handle *
547 GNUNET_MQ_queue_for_callbacks (GNUNET_MQ_SendImpl send,
548                                GNUNET_MQ_DestroyImpl destroy,
549                                GNUNET_MQ_CancelImpl cancel,
550                                void *impl_state,
551                                const struct GNUNET_MQ_MessageHandler *handlers,
552                                GNUNET_MQ_ErrorHandler error_handler,
553                                void *error_handler_cls)
554 {
555   struct GNUNET_MQ_Handle *mq;
556
557   mq = GNUNET_new (struct GNUNET_MQ_Handle);
558   mq->send_impl = send;
559   mq->destroy_impl = destroy;
560   mq->cancel_impl = cancel;
561   mq->handlers = GNUNET_MQ_copy_handlers (handlers);
562   mq->error_handler = error_handler;
563   mq->error_handler_cls = error_handler_cls;
564   mq->impl_state = impl_state;
565
566   return mq;
567 }
568
569
570 /**
571  * Change the closure argument in all of the `handlers` of the
572  * @a mq.
573  *
574  * @param mq to modify
575  * @param handlers_cls new closure to use
576  */
577 void
578 GNUNET_MQ_set_handlers_closure (struct GNUNET_MQ_Handle *mq,
579                                 void *handlers_cls)
580 {
581   if (NULL == mq->handlers)
582     return;
583   for (unsigned int i=0;NULL != mq->handlers[i].cb; i++)
584     mq->handlers[i].cls = handlers_cls;
585 }
586
587
588 /**
589  * Get the message that should currently be sent.
590  * Fails if there is no current message.
591  * Only useful for implementing message queues,
592  * results in undefined behavior if not used carefully.
593  *
594  * @param mq message queue with the current message
595  * @return message to send, never NULL
596  */
597 const struct GNUNET_MessageHeader *
598 GNUNET_MQ_impl_current (struct GNUNET_MQ_Handle *mq)
599 {
600   GNUNET_assert (NULL != mq->current_envelope);
601   GNUNET_assert (NULL != mq->current_envelope->mh);
602   return mq->current_envelope->mh;
603 }
604
605
606 /**
607  * Get the implementation state associated with the
608  * message queue.
609  *
610  * While the GNUNET_MQ_Impl* callbacks receive the
611  * implementation state, continuations that are scheduled
612  * by the implementation function often only have one closure
613  * argument, with this function it is possible to get at the
614  * implementation state when only passing the GNUNET_MQ_Handle
615  * as closure.
616  *
617  * @param mq message queue with the current message
618  * @return message to send, never NULL
619  */
620 void *
621 GNUNET_MQ_impl_state (struct GNUNET_MQ_Handle *mq)
622 {
623   return mq->impl_state;
624 }
625
626
627 struct GNUNET_MQ_Envelope *
628 GNUNET_MQ_msg_ (struct GNUNET_MessageHeader **mhp,
629                 uint16_t size,
630                 uint16_t type)
631 {
632   struct GNUNET_MQ_Envelope *ev;
633
634   ev = GNUNET_malloc (size + sizeof (struct GNUNET_MQ_Envelope));
635   ev->mh = (struct GNUNET_MessageHeader *) &ev[1];
636   ev->mh->size = htons (size);
637   ev->mh->type = htons (type);
638   if (NULL != mhp)
639     *mhp = ev->mh;
640   return ev;
641 }
642
643
644 /**
645  * Create a new envelope by copying an existing message.
646  *
647  * @param hdr header of the message to copy
648  * @return envelope containing @a hdr
649  */
650 struct GNUNET_MQ_Envelope *
651 GNUNET_MQ_msg_copy (const struct GNUNET_MessageHeader *hdr)
652 {
653   struct GNUNET_MQ_Envelope *mqm;
654   uint16_t size = ntohs (hdr->size);
655
656   mqm = GNUNET_malloc (sizeof (*mqm) + size);
657   mqm->mh = (struct GNUNET_MessageHeader *) &mqm[1];
658   GNUNET_memcpy (mqm->mh,
659           hdr,
660           size);
661   return mqm;
662 }
663
664
665 /**
666  * Implementation of the #GNUNET_MQ_msg_nested_mh macro.
667  *
668  * @param mhp pointer to the message header pointer that will be changed to allocate at
669  *        the newly allocated space for the message.
670  * @param base_size size of the data before the nested message
671  * @param type type of the message in the envelope
672  * @param nested_mh the message to append to the message after base_size
673  */
674 struct GNUNET_MQ_Envelope *
675 GNUNET_MQ_msg_nested_mh_ (struct GNUNET_MessageHeader **mhp,
676                           uint16_t base_size,
677                           uint16_t type,
678                           const struct GNUNET_MessageHeader *nested_mh)
679 {
680   struct GNUNET_MQ_Envelope *mqm;
681   uint16_t size;
682
683   if (NULL == nested_mh)
684     return GNUNET_MQ_msg_ (mhp, base_size, type);
685
686   size = base_size + ntohs (nested_mh->size);
687
688   /* check for uint16_t overflow */
689   if (size < base_size)
690     return NULL;
691
692   mqm = GNUNET_MQ_msg_ (mhp, size, type);
693   GNUNET_memcpy ((char *) mqm->mh + base_size,
694                  nested_mh,
695                  ntohs (nested_mh->size));
696
697   return mqm;
698 }
699
700
701 /**
702  * Associate the assoc_data in mq with a unique request id.
703  *
704  * @param mq message queue, id will be unique for the queue
705  * @param assoc_data to associate
706  */
707 uint32_t
708 GNUNET_MQ_assoc_add (struct GNUNET_MQ_Handle *mq,
709                      void *assoc_data)
710 {
711   uint32_t id;
712
713   if (NULL == mq->assoc_map)
714   {
715     mq->assoc_map = GNUNET_CONTAINER_multihashmap32_create (8);
716     mq->assoc_id = 1;
717   }
718   id = mq->assoc_id++;
719   GNUNET_assert (GNUNET_OK ==
720                  GNUNET_CONTAINER_multihashmap32_put (mq->assoc_map,
721                                                       id,
722                                                       assoc_data,
723                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
724   return id;
725 }
726
727
728 /**
729  * Get the data associated with a @a request_id in a queue
730  *
731  * @param mq the message queue with the association
732  * @param request_id the request id we are interested in
733  * @return the associated data
734  */
735 void *
736 GNUNET_MQ_assoc_get (struct GNUNET_MQ_Handle *mq,
737                      uint32_t request_id)
738 {
739   if (NULL == mq->assoc_map)
740     return NULL;
741   return GNUNET_CONTAINER_multihashmap32_get (mq->assoc_map,
742                                               request_id);
743 }
744
745
746 /**
747  * Remove the association for a @a request_id
748  *
749  * @param mq the message queue with the association
750  * @param request_id the request id we want to remove
751  * @return the associated data
752  */
753 void *
754 GNUNET_MQ_assoc_remove (struct GNUNET_MQ_Handle *mq,
755                         uint32_t request_id)
756 {
757   void *val;
758
759   if (NULL == mq->assoc_map)
760     return NULL;
761   val = GNUNET_CONTAINER_multihashmap32_get (mq->assoc_map,
762                                              request_id);
763   GNUNET_CONTAINER_multihashmap32_remove_all (mq->assoc_map,
764                                               request_id);
765   return val;
766 }
767
768
769 /**
770  * Call a callback once the envelope has been sent, that is,
771  * sending it can not be canceled anymore.
772  * There can be only one notify sent callback per envelope.
773  *
774  * @param ev message to call the notify callback for
775  * @param cb the notify callback
776  * @param cb_cls closure for the callback
777  */
778 void
779 GNUNET_MQ_notify_sent (struct GNUNET_MQ_Envelope *ev,
780                        GNUNET_SCHEDULER_TaskCallback cb,
781                        void *cb_cls)
782 {
783   /* allow setting *OR* clearing callback */
784   GNUNET_assert ( (NULL == ev->sent_cb) ||
785                   (NULL == cb) );
786   ev->sent_cb = cb;
787   ev->sent_cls = cb_cls;
788 }
789
790
791 /**
792  * Handle we return for callbacks registered to be
793  * notified when #GNUNET_MQ_destroy() is called on a queue.
794  */
795 struct GNUNET_MQ_DestroyNotificationHandle
796 {
797   /**
798    * Kept in a DLL.
799    */
800   struct GNUNET_MQ_DestroyNotificationHandle *prev;
801
802   /**
803    * Kept in a DLL.
804    */
805   struct GNUNET_MQ_DestroyNotificationHandle *next;
806
807   /**
808    * Queue to notify about.
809    */
810   struct GNUNET_MQ_Handle *mq;
811
812   /**
813    * Function to call.
814    */
815   GNUNET_SCHEDULER_TaskCallback cb;
816
817   /**
818    * Closure for @e cb.
819    */
820   void *cb_cls;
821 };
822
823
824 /**
825  * Destroy the message queue.
826  *
827  * @param mq message queue to destroy
828  */
829 void
830 GNUNET_MQ_destroy (struct GNUNET_MQ_Handle *mq)
831 {
832   struct GNUNET_MQ_DestroyNotificationHandle *dnh;
833
834   if (NULL != mq->destroy_impl)
835   {
836     mq->destroy_impl (mq, mq->impl_state);
837   }
838   if (NULL != mq->send_task)
839   {
840     GNUNET_SCHEDULER_cancel (mq->send_task);
841     mq->send_task = NULL;
842   }
843   while (NULL != mq->envelope_head)
844   {
845     struct GNUNET_MQ_Envelope *ev;
846
847     ev = mq->envelope_head;
848     ev->parent_queue = NULL;
849     GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
850                                  mq->envelope_tail,
851                                  ev);
852     GNUNET_assert (0 < mq->queue_length);
853     mq->queue_length--;
854     LOG (GNUNET_ERROR_TYPE_DEBUG,
855          "MQ destroy drops message of type %u\n",
856          ntohs (ev->mh->type));
857     GNUNET_MQ_discard (ev);
858   }
859   if (NULL != mq->current_envelope)
860   {
861     /* we can only discard envelopes that
862      * are not queued! */
863     mq->current_envelope->parent_queue = NULL;
864     LOG (GNUNET_ERROR_TYPE_DEBUG,
865          "MQ destroy drops current message of type %u\n",
866          ntohs (mq->current_envelope->mh->type));
867     GNUNET_MQ_discard (mq->current_envelope);
868     mq->current_envelope = NULL;
869     GNUNET_assert (0 < mq->queue_length);
870     mq->queue_length--;
871   }
872   GNUNET_assert (0 == mq->queue_length);
873   while (NULL != (dnh = mq->dnh_head))
874   {
875     dnh->cb (dnh->cb_cls);
876     GNUNET_MQ_destroy_notify_cancel (dnh);
877   }
878   if (NULL != mq->assoc_map)
879   {
880     GNUNET_CONTAINER_multihashmap32_destroy (mq->assoc_map);
881     mq->assoc_map = NULL;
882   }
883   GNUNET_free_non_null (mq->handlers);
884   GNUNET_free (mq);
885 }
886
887
888 const struct GNUNET_MessageHeader *
889 GNUNET_MQ_extract_nested_mh_ (const struct GNUNET_MessageHeader *mh,
890                               uint16_t base_size)
891 {
892   uint16_t whole_size;
893   uint16_t nested_size;
894   const struct GNUNET_MessageHeader *nested_msg;
895
896   whole_size = ntohs (mh->size);
897   GNUNET_assert (whole_size >= base_size);
898   nested_size = whole_size - base_size;
899   if (0 == nested_size)
900     return NULL;
901   if (nested_size < sizeof (struct GNUNET_MessageHeader))
902   {
903     GNUNET_break_op (0);
904     return NULL;
905   }
906   nested_msg = (const struct GNUNET_MessageHeader *) ((char *) mh + base_size);
907   if (ntohs (nested_msg->size) != nested_size)
908   {
909     GNUNET_break_op (0);
910     return NULL;
911   }
912   return nested_msg;
913 }
914
915
916 /**
917  * Cancel sending the message. Message must have been sent with
918  * #GNUNET_MQ_send before.  May not be called after the notify sent
919  * callback has been called
920  *
921  * @param ev queued envelope to cancel
922  */
923 void
924 GNUNET_MQ_send_cancel (struct GNUNET_MQ_Envelope *ev)
925 {
926   struct GNUNET_MQ_Handle *mq = ev->parent_queue;
927
928   GNUNET_assert (NULL != mq);
929   GNUNET_assert (NULL != mq->cancel_impl);
930
931   mq->evacuate_called = GNUNET_NO;
932
933   if (mq->current_envelope == ev)
934   {
935     /* complex case, we already started with transmitting
936        the message using the callbacks. */
937     GNUNET_assert (0 < mq->queue_length);
938     mq->queue_length--;
939     mq->cancel_impl (mq,
940                      mq->impl_state);
941     /* continue sending the next message, if any */
942     mq->current_envelope = mq->envelope_head;
943     if (NULL != mq->current_envelope)
944     {
945       GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
946                                    mq->envelope_tail,
947                                    mq->current_envelope);
948
949       LOG (GNUNET_ERROR_TYPE_DEBUG,
950            "sending canceled message of type %u queue\n",
951            ntohs(ev->mh->type));
952
953       mq->send_impl (mq,
954                      mq->current_envelope->mh,
955                      mq->impl_state);
956     }
957   }
958   else
959   {
960     /* simple case, message is still waiting in the queue */
961     GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
962                                  mq->envelope_tail,
963                                  ev);
964     GNUNET_assert (0 < mq->queue_length);
965     mq->queue_length--;
966   }
967
968   if (GNUNET_YES != mq->evacuate_called)
969   {
970     ev->parent_queue = NULL;
971     ev->mh = NULL;
972     /* also frees ev */
973     GNUNET_free (ev);
974   }
975 }
976
977
978 /**
979  * Function to obtain the current envelope
980  * from within #GNUNET_MQ_SendImpl implementations.
981  *
982  * @param mq message queue to interrogate
983  * @return the current envelope
984  */
985 struct GNUNET_MQ_Envelope *
986 GNUNET_MQ_get_current_envelope (struct GNUNET_MQ_Handle *mq)
987 {
988   return mq->current_envelope;
989 }
990
991
992 /**
993  * Function to obtain the last envelope in the queue.
994  *
995  * @param mq message queue to interrogate
996  * @return the last envelope in the queue
997  */
998 struct GNUNET_MQ_Envelope *
999 GNUNET_MQ_get_last_envelope (struct GNUNET_MQ_Handle *mq)
1000 {
1001   if (NULL != mq->envelope_tail)
1002     return mq->envelope_tail;
1003
1004   return mq->current_envelope;
1005 }
1006
1007
1008 /**
1009  * Set application-specific options for this envelope.
1010  * Overrides the options set for the queue with
1011  * #GNUNET_MQ_set_options() for this message only.
1012  *
1013  * @param env message to set options for
1014  * @param flags flags to use (meaning is queue-specific)
1015  * @param extra additional buffer for further data (also queue-specific)
1016  */
1017 void
1018 GNUNET_MQ_env_set_options (struct GNUNET_MQ_Envelope *env,
1019                            uint64_t flags,
1020                            const void *extra)
1021 {
1022   env->flags = flags;
1023   env->extra = extra;
1024   env->have_custom_options = GNUNET_YES;
1025 }
1026
1027
1028 /**
1029  * Get application-specific options for this envelope.
1030  *
1031  * @param env message to set options for
1032  * @param[out] flags set to flags to use (meaning is queue-specific)
1033  * @return extra additional buffer for further data (also queue-specific)
1034  */
1035 const void *
1036 GNUNET_MQ_env_get_options (struct GNUNET_MQ_Envelope *env,
1037                            uint64_t *flags)
1038 {
1039   struct GNUNET_MQ_Handle *mq = env->parent_queue;
1040
1041   if (GNUNET_YES == env->have_custom_options)
1042   {
1043     *flags = env->flags;
1044     return env->extra;
1045   }
1046   if (NULL == mq)
1047   {
1048     *flags = 0;
1049     return NULL;
1050   }
1051   *flags = mq->default_flags;
1052   return mq->default_extra;
1053 }
1054
1055
1056 /**
1057  * Set application-specific options for this queue.
1058  *
1059  * @param mq message queue to set options for
1060  * @param flags flags to use (meaning is queue-specific)
1061  * @param extra additional buffer for further data (also queue-specific)
1062  */
1063 void
1064 GNUNET_MQ_set_options (struct GNUNET_MQ_Handle *mq,
1065                        uint64_t flags,
1066                        const void *extra)
1067 {
1068   mq->default_flags = flags;
1069   mq->default_extra = extra;
1070 }
1071
1072
1073 /**
1074  * Register function to be called whenever @a mq is being
1075  * destroyed.
1076  *
1077  * @param mq message queue to watch
1078  * @param cb function to call on @a mq destruction
1079  * @param cb_cls closure for @a cb
1080  * @return handle for #GNUNET_MQ_destroy_notify_cancel().
1081  */
1082 struct GNUNET_MQ_DestroyNotificationHandle *
1083 GNUNET_MQ_destroy_notify (struct GNUNET_MQ_Handle *mq,
1084                           GNUNET_SCHEDULER_TaskCallback cb,
1085                           void *cb_cls)
1086 {
1087   struct GNUNET_MQ_DestroyNotificationHandle *dnh;
1088
1089   dnh = GNUNET_new (struct GNUNET_MQ_DestroyNotificationHandle);
1090   dnh->mq = mq;
1091   dnh->cb = cb;
1092   dnh->cb_cls = cb_cls;
1093   GNUNET_CONTAINER_DLL_insert (mq->dnh_head,
1094                                mq->dnh_tail,
1095                                dnh);
1096   return dnh;
1097 }
1098
1099
1100 /**
1101  * Cancel registration from #GNUNET_MQ_destroy_notify().
1102  *
1103  * @param dnh handle for registration to cancel
1104  */
1105 void
1106 GNUNET_MQ_destroy_notify_cancel (struct GNUNET_MQ_DestroyNotificationHandle *dnh)
1107 {
1108   struct GNUNET_MQ_Handle *mq = dnh->mq;
1109
1110   GNUNET_CONTAINER_DLL_remove (mq->dnh_head,
1111                                mq->dnh_tail,
1112                                dnh);
1113   GNUNET_free (dnh);
1114 }
1115
1116
1117 /**
1118  * Insert @a env into the envelope DLL starting at @a env_head
1119  * Note that @a env must not be in any MQ while this function
1120  * is used with DLLs defined outside of the MQ module.  This
1121  * is just in case some application needs to also manage a
1122  * FIFO of envelopes independent of MQ itself and wants to
1123  * re-use the pointers internal to @a env.  Use with caution.
1124  *
1125  * @param[in|out] env_head of envelope DLL
1126  * @param[in|out] env_tail tail of envelope DLL
1127  * @param[in|out] env element to insert at the tail
1128  */
1129 void
1130 GNUNET_MQ_dll_insert_tail (struct GNUNET_MQ_Envelope **env_head,
1131                            struct GNUNET_MQ_Envelope **env_tail,
1132                            struct GNUNET_MQ_Envelope *env)
1133 {
1134   GNUNET_CONTAINER_DLL_insert_tail (*env_head,
1135                                     *env_tail,
1136                                     env);
1137 }
1138
1139
1140 /**
1141  * Remove @a env from the envelope DLL starting at @a env_head.
1142  * Note that @a env must not be in any MQ while this function
1143  * is used with DLLs defined outside of the MQ module. This
1144  * is just in case some application needs to also manage a
1145  * FIFO of envelopes independent of MQ itself and wants to
1146  * re-use the pointers internal to @a env.  Use with caution.
1147  *
1148  * @param[in|out] env_head of envelope DLL
1149  * @param[in|out] env_tail tail of envelope DLL
1150  * @param[in|out] env element to remove from the DLL
1151  */
1152 void
1153 GNUNET_MQ_dll_remove (struct GNUNET_MQ_Envelope **env_head,
1154                       struct GNUNET_MQ_Envelope **env_tail,
1155                       struct GNUNET_MQ_Envelope *env)
1156 {
1157   GNUNET_CONTAINER_DLL_remove (*env_head,
1158                                *env_tail,
1159                                env);
1160 }
1161
1162
1163 /**
1164  * Copy an array of handlers.
1165  *
1166  * Useful if the array has been delared in local memory and needs to be
1167  * persisted for future use.
1168  *
1169  * @param handlers Array of handlers to be copied. Can be NULL (nothing done).
1170  * @return A newly allocated array of handlers.
1171  *         Needs to be freed with #GNUNET_free.
1172  */
1173 struct GNUNET_MQ_MessageHandler *
1174 GNUNET_MQ_copy_handlers (const struct GNUNET_MQ_MessageHandler *handlers)
1175 {
1176   struct GNUNET_MQ_MessageHandler *copy;
1177   unsigned int count;
1178
1179   if (NULL == handlers)
1180     return NULL;
1181
1182   count = GNUNET_MQ_count_handlers (handlers);
1183   copy = GNUNET_new_array (count + 1,
1184                            struct GNUNET_MQ_MessageHandler);
1185   GNUNET_memcpy (copy,
1186                  handlers,
1187                  count * sizeof (struct GNUNET_MQ_MessageHandler));
1188   return copy;
1189 }
1190
1191
1192 /**
1193  * Count the handlers in a handler array.
1194  *
1195  * @param handlers Array of handlers to be counted.
1196  * @return The number of handlers in the array.
1197  */
1198 unsigned int
1199 GNUNET_MQ_count_handlers (const struct GNUNET_MQ_MessageHandler *handlers)
1200 {
1201   unsigned int i;
1202
1203   if (NULL == handlers)
1204     return 0;
1205
1206   for (i=0; NULL != handlers[i].cb; i++) ;
1207
1208   return i;
1209 }
1210
1211
1212
1213 /* end of mq.c */