More API function tests...
[oweals/gnunet.git] / src / util / mq.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012-2014 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, "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  * Implementation-specific state for connection to
206  * client (MQ for server).
207  */
208 struct ServerClientSocketState
209 {
210   /**
211    * Handle of the client that connected to the server.
212    */
213   struct GNUNET_SERVER_Client *client;
214
215   /**
216    * Active transmission request to the client.
217    */
218   struct GNUNET_SERVER_TransmitHandle *th;
219 };
220
221
222 /**
223  * Call the message message handler that was registered
224  * for the type of the given message in the given message queue.
225  *
226  * This function is indended to be used for the implementation
227  * of message queues.
228  *
229  * @param mq message queue with the handlers
230  * @param mh message to dispatch
231  */
232 void
233 GNUNET_MQ_inject_message (struct GNUNET_MQ_Handle *mq,
234                           const struct GNUNET_MessageHeader *mh)
235 {
236   const struct GNUNET_MQ_MessageHandler *handler;
237   int handled = GNUNET_NO;
238   uint16_t ms = ntohs (mh->size);
239
240   if (NULL == mq->handlers)
241     goto done;
242   for (handler = mq->handlers; NULL != handler->cb; handler++)
243   {
244     if (handler->type == ntohs (mh->type))
245     {
246       handled = GNUNET_YES;
247       if ( (handler->expected_size > ms) ||
248            ( (handler->expected_size != ms) &&
249              (NULL == handler->mv) ) )
250       {
251         /* Too small, or not an exact size and
252            no 'mv' handler to check rest */
253         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
254                     "Received malformed message of type %u\n",
255                     (unsigned int) handler->type);
256         GNUNET_MQ_inject_error (mq,
257                                 GNUNET_MQ_ERROR_MALFORMED);
258         break;
259       }
260       if ( (NULL == handler->mv) ||
261            (GNUNET_OK ==
262             handler->mv (handler->cls, mh)) )
263       {
264         /* message well-formed, pass to handler */
265         handler->cb (handler->cls, mh);
266       }
267       else
268       {
269         /* Message rejected by check routine */
270         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
271                     "Received malformed message of type %u\n",
272                     (unsigned int) handler->type);
273         GNUNET_MQ_inject_error (mq,
274                                 GNUNET_MQ_ERROR_MALFORMED);
275       }
276       break;
277     }
278   }
279  done:
280   if (GNUNET_NO == handled)
281     LOG (GNUNET_ERROR_TYPE_INFO,
282          "No handler for message of type %d and size %d\n",
283          ntohs (mh->type),
284          ntohs (mh->size));
285 }
286
287
288 /**
289  * Call the error handler of a message queue with the given
290  * error code.  If there is no error handler, log a warning.
291  *
292  * This function is intended to be used by the implementation
293  * of message queues.
294  *
295  * @param mq message queue
296  * @param error the error type
297  */
298 void
299 GNUNET_MQ_inject_error (struct GNUNET_MQ_Handle *mq,
300                         enum GNUNET_MQ_Error error)
301 {
302   if (NULL == mq->error_handler)
303   {
304     LOG (GNUNET_ERROR_TYPE_WARNING,
305          "Got error %d, but no handler installed\n",
306          (int) error);
307     return;
308   }
309   mq->error_handler (mq->error_handler_cls,
310                      error);
311 }
312
313
314 /**
315  * Discard the message queue message, free all
316  * allocated resources. Must be called in the event
317  * that a message is created but should not actually be sent.
318  *
319  * @param mqm the message to discard
320  */
321 void
322 GNUNET_MQ_discard (struct GNUNET_MQ_Envelope *ev)
323 {
324   GNUNET_assert (NULL == ev->parent_queue);
325   GNUNET_free (ev);
326 }
327
328
329 /**
330  * Obtain the current length of the message queue.
331  *
332  * @param mq queue to inspect
333  * @return number of queued, non-transmitted messages
334  */
335 unsigned int
336 GNUNET_MQ_get_length (struct GNUNET_MQ_Handle *mq)
337 {
338   if (GNUNET_YES != mq->in_flight)
339   {
340     return mq->queue_length;
341   }
342   return mq->queue_length - 1;
343 }
344
345
346 /**
347  * Send a message with the given message queue.
348  * May only be called once per message.
349  *
350  * @param mq message queue
351  * @param ev the envelope with the message to send.
352  */
353 void
354 GNUNET_MQ_send (struct GNUNET_MQ_Handle *mq,
355                 struct GNUNET_MQ_Envelope *ev)
356 {
357   GNUNET_assert (NULL != mq);
358   GNUNET_assert (NULL == ev->parent_queue);
359
360   mq->queue_length++;
361   ev->parent_queue = mq;
362   /* is the implementation busy? queue it! */
363   if ( (NULL != mq->current_envelope) ||
364        (NULL != mq->send_task) )
365   {
366     GNUNET_CONTAINER_DLL_insert_tail (mq->envelope_head,
367                                       mq->envelope_tail,
368                                       ev);
369     return;
370   }
371   GNUNET_assert (NULL == mq->envelope_head);
372   mq->current_envelope = ev;
373   mq->send_impl (mq,
374                  ev->mh,
375                  mq->impl_state);
376 }
377
378
379 /**
380  * Send a copy of a message with the given message queue.
381  * Can be called repeatedly on the same envelope.
382  *
383  * @param mq message queue
384  * @param ev the envelope with the message to send.
385  */
386 void
387 GNUNET_MQ_send_copy (struct GNUNET_MQ_Handle *mq,
388                      const struct GNUNET_MQ_Envelope *ev)
389 {
390   struct GNUNET_MQ_Envelope *env;
391   uint16_t msize;
392
393   msize = ntohs (ev->mh->size);
394   env = GNUNET_malloc (sizeof (struct GNUNET_MQ_Envelope) +
395                        msize);
396   env->mh = (struct GNUNET_MessageHeader *) &env[1];
397   env->sent_cb = ev->sent_cb;
398   env->sent_cls = ev->sent_cls;
399   GNUNET_memcpy (&env[1],
400           ev->mh,
401           msize);
402   GNUNET_MQ_send (mq,
403                   env);
404 }
405
406
407 /**
408  * Task run to call the send implementation for the next queued
409  * message, if any.  Only useful for implementing message queues,
410  * results in undefined behavior if not used carefully.
411  *
412  * @param cls message queue to send the next message with
413  */
414 static void
415 impl_send_continue (void *cls)
416 {
417   struct GNUNET_MQ_Handle *mq = cls;
418
419   mq->send_task = NULL;
420   /* call is only valid if we're actually currently sending
421    * a message */
422   if (NULL == mq->envelope_head)
423     return;
424   mq->current_envelope = mq->envelope_head;
425   GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
426                                mq->envelope_tail,
427                                mq->current_envelope);
428   mq->send_impl (mq,
429                  mq->current_envelope->mh,
430                  mq->impl_state);
431 }
432
433
434 /**
435  * Call the send implementation for the next queued message, if any.
436  * Only useful for implementing message queues, results in undefined
437  * behavior if not used carefully.
438  *
439  * @param mq message queue to send the next message with
440  */
441 void
442 GNUNET_MQ_impl_send_continue (struct GNUNET_MQ_Handle *mq)
443 {
444   struct GNUNET_MQ_Envelope *current_envelope;
445   GNUNET_SCHEDULER_TaskCallback cb;
446
447   GNUNET_assert (0 < mq->queue_length);
448   mq->queue_length--;
449   mq->in_flight = GNUNET_NO;
450   current_envelope = mq->current_envelope;
451   current_envelope->parent_queue = NULL;
452   mq->current_envelope = NULL;
453   GNUNET_assert (NULL == mq->send_task);
454   mq->send_task = GNUNET_SCHEDULER_add_now (&impl_send_continue,
455                                             mq);
456   if (NULL != (cb = current_envelope->sent_cb))
457   {
458     current_envelope->sent_cb = NULL;
459     cb (current_envelope->sent_cls);
460   }
461   GNUNET_free (current_envelope);
462 }
463
464
465 /**
466  * Call the send notification for the current message, but do not
467  * try to send the next message until #GNUNET_MQ_impl_send_continue
468  * is called.
469  *
470  * Only useful for implementing message queues, results in undefined
471  * behavior if not used carefully.
472  *
473  * @param mq message queue to send the next message with
474  */
475 void
476 GNUNET_MQ_impl_send_in_flight (struct GNUNET_MQ_Handle *mq)
477 {
478   struct GNUNET_MQ_Envelope *current_envelope;
479   GNUNET_SCHEDULER_TaskCallback cb;
480
481   mq->in_flight = GNUNET_YES;
482   /* call is only valid if we're actually currently sending
483    * a message */
484   current_envelope = mq->current_envelope;
485   GNUNET_assert (NULL != current_envelope);
486   /* can't call cancel from now on anymore */
487   current_envelope->parent_queue = NULL;
488   if (NULL != (cb = current_envelope->sent_cb))
489   {
490     current_envelope->sent_cb = NULL;
491     cb (current_envelope->sent_cls);
492   }
493 }
494
495
496 /**
497  * Create a message queue for the specified handlers.
498  *
499  * @param send function the implements sending messages
500  * @param destroy function that implements destroying the queue
501  * @param cancel function that implements canceling a message
502  * @param impl_state for the queue, passed to 'send' and 'destroy'
503  * @param handlers array of message handlers
504  * @param error_handler handler for read and write errors
505  * @param error_handler_cls closure for @a error_handler
506  * @return a new message queue
507  */
508 struct GNUNET_MQ_Handle *
509 GNUNET_MQ_queue_for_callbacks (GNUNET_MQ_SendImpl send,
510                                GNUNET_MQ_DestroyImpl destroy,
511                                GNUNET_MQ_CancelImpl cancel,
512                                void *impl_state,
513                                const struct GNUNET_MQ_MessageHandler *handlers,
514                                GNUNET_MQ_ErrorHandler error_handler,
515                                void *error_handler_cls)
516 {
517   struct GNUNET_MQ_Handle *mq;
518
519   mq = GNUNET_new (struct GNUNET_MQ_Handle);
520   mq->send_impl = send;
521   mq->destroy_impl = destroy;
522   mq->cancel_impl = cancel;
523   mq->handlers = GNUNET_MQ_copy_handlers (handlers);
524   mq->error_handler = error_handler;
525   mq->error_handler_cls = error_handler_cls;
526   mq->impl_state = impl_state;
527
528   return mq;
529 }
530
531
532 /**
533  * Change the closure argument in all of the `handlers` of the
534  * @a mq.
535  *
536  * @param mq to modify
537  * @param handlers_cls new closure to use
538  */
539 void
540 GNUNET_MQ_set_handlers_closure (struct GNUNET_MQ_Handle *mq,
541                                 void *handlers_cls)
542 {
543   unsigned int i;
544
545   if (NULL == mq->handlers)
546     return;
547   for (i=0;NULL != mq->handlers[i].cb; i++)
548     mq->handlers[i].cls = handlers_cls;
549 }
550
551
552 /**
553  * Get the message that should currently be sent.
554  * Fails if there is no current message.
555  * Only useful for implementing message queues,
556  * results in undefined behavior if not used carefully.
557  *
558  * @param mq message queue with the current message
559  * @return message to send, never NULL
560  */
561 const struct GNUNET_MessageHeader *
562 GNUNET_MQ_impl_current (struct GNUNET_MQ_Handle *mq)
563 {
564   GNUNET_assert (NULL != mq->current_envelope);
565   GNUNET_assert (NULL != mq->current_envelope->mh);
566   return mq->current_envelope->mh;
567 }
568
569
570 /**
571  * Get the implementation state associated with the
572  * message queue.
573  *
574  * While the GNUNET_MQ_Impl* callbacks receive the
575  * implementation state, continuations that are scheduled
576  * by the implementation function often only have one closure
577  * argument, with this function it is possible to get at the
578  * implementation state when only passing the GNUNET_MQ_Handle
579  * as closure.
580  *
581  * @param mq message queue with the current message
582  * @return message to send, never NULL
583  */
584 void *
585 GNUNET_MQ_impl_state (struct GNUNET_MQ_Handle *mq)
586 {
587   return mq->impl_state;
588 }
589
590
591 struct GNUNET_MQ_Envelope *
592 GNUNET_MQ_msg_ (struct GNUNET_MessageHeader **mhp,
593                 uint16_t size,
594                 uint16_t type)
595 {
596   struct GNUNET_MQ_Envelope *ev;
597
598   ev = GNUNET_malloc (size + sizeof (struct GNUNET_MQ_Envelope));
599   ev->mh = (struct GNUNET_MessageHeader *) &ev[1];
600   ev->mh->size = htons (size);
601   ev->mh->type = htons (type);
602   if (NULL != mhp)
603     *mhp = ev->mh;
604   return ev;
605 }
606
607
608 /**
609  * Create a new envelope by copying an existing message.
610  *
611  * @param hdr header of the message to copy
612  * @return envelope containing @a hdr
613  */
614 struct GNUNET_MQ_Envelope *
615 GNUNET_MQ_msg_copy (const struct GNUNET_MessageHeader *hdr)
616 {
617   struct GNUNET_MQ_Envelope *mqm;
618   uint16_t size = ntohs (hdr->size);
619
620   mqm = GNUNET_malloc (sizeof (*mqm) + size);
621   mqm->mh = (struct GNUNET_MessageHeader *) &mqm[1];
622   GNUNET_memcpy (mqm->mh,
623           hdr,
624           size);
625   return mqm;
626 }
627
628
629 /**
630  * Implementation of the #GNUNET_MQ_msg_nested_mh macro.
631  *
632  * @param mhp pointer to the message header pointer that will be changed to allocate at
633  *        the newly allocated space for the message.
634  * @param base_size size of the data before the nested message
635  * @param type type of the message in the envelope
636  * @param nested_mh the message to append to the message after base_size
637  */
638 struct GNUNET_MQ_Envelope *
639 GNUNET_MQ_msg_nested_mh_ (struct GNUNET_MessageHeader **mhp,
640                           uint16_t base_size,
641                           uint16_t type,
642                           const struct GNUNET_MessageHeader *nested_mh)
643 {
644   struct GNUNET_MQ_Envelope *mqm;
645   uint16_t size;
646
647   if (NULL == nested_mh)
648     return GNUNET_MQ_msg_ (mhp, base_size, type);
649
650   size = base_size + ntohs (nested_mh->size);
651
652   /* check for uint16_t overflow */
653   if (size < base_size)
654     return NULL;
655
656   mqm = GNUNET_MQ_msg_ (mhp, size, type);
657   GNUNET_memcpy ((char *) mqm->mh + base_size,
658                  nested_mh,
659                  ntohs (nested_mh->size));
660
661   return mqm;
662 }
663
664
665 /**
666  * Transmit a queued message to the session's client.
667  *
668  * @param cls consensus session
669  * @param size number of bytes available in @a buf
670  * @param buf where the callee should write the message
671  * @return number of bytes written to @a buf
672  */
673 static size_t
674 transmit_queued (void *cls,
675                  size_t size,
676                  void *buf)
677 {
678   struct GNUNET_MQ_Handle *mq = cls;
679   struct ServerClientSocketState *state = GNUNET_MQ_impl_state (mq);
680   const struct GNUNET_MessageHeader *msg = GNUNET_MQ_impl_current (mq);
681   size_t msg_size;
682
683   GNUNET_assert (NULL != buf);
684   msg_size = ntohs (msg->size);
685   GNUNET_assert (size >= msg_size);
686   GNUNET_memcpy (buf, msg, msg_size);
687   state->th = NULL;
688
689   GNUNET_MQ_impl_send_continue (mq);
690
691   return msg_size;
692 }
693
694
695 static void
696 server_client_destroy_impl (struct GNUNET_MQ_Handle *mq,
697                             void *impl_state)
698 {
699   struct ServerClientSocketState *state = impl_state;
700
701   if (NULL != state->th)
702   {
703     GNUNET_SERVER_notify_transmit_ready_cancel (state->th);
704     state->th = NULL;
705   }
706
707   GNUNET_assert (NULL != mq);
708   GNUNET_assert (NULL != state);
709   GNUNET_SERVER_client_drop (state->client);
710   GNUNET_free (state);
711 }
712
713
714 static void
715 server_client_send_impl (struct GNUNET_MQ_Handle *mq,
716                          const struct GNUNET_MessageHeader *msg,
717                          void *impl_state)
718 {
719   struct ServerClientSocketState *state = impl_state;
720
721   GNUNET_assert (NULL != mq);
722   state->th = GNUNET_SERVER_notify_transmit_ready (state->client,
723                                                    ntohs (msg->size),
724                                                    GNUNET_TIME_UNIT_FOREVER_REL,
725                                                    &transmit_queued,
726                                                    mq);
727 }
728
729
730 struct GNUNET_MQ_Handle *
731 GNUNET_MQ_queue_for_server_client (struct GNUNET_SERVER_Client *client)
732 {
733   struct GNUNET_MQ_Handle *mq;
734   struct ServerClientSocketState *scss;
735
736   mq = GNUNET_new (struct GNUNET_MQ_Handle);
737   scss = GNUNET_new (struct ServerClientSocketState);
738   mq->impl_state = scss;
739   scss->client = client;
740   GNUNET_SERVER_client_keep (client);
741   mq->send_impl = &server_client_send_impl;
742   mq->destroy_impl = &server_client_destroy_impl;
743   return mq;
744 }
745
746
747 /**
748  * Associate the assoc_data in mq with a unique request id.
749  *
750  * @param mq message queue, id will be unique for the queue
751  * @param assoc_data to associate
752  */
753 uint32_t
754 GNUNET_MQ_assoc_add (struct GNUNET_MQ_Handle *mq,
755                      void *assoc_data)
756 {
757   uint32_t id;
758
759   if (NULL == mq->assoc_map)
760   {
761     mq->assoc_map = GNUNET_CONTAINER_multihashmap32_create (8);
762     mq->assoc_id = 1;
763   }
764   id = mq->assoc_id++;
765   GNUNET_CONTAINER_multihashmap32_put (mq->assoc_map, id, assoc_data,
766                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
767   return id;
768 }
769
770
771 void *
772 GNUNET_MQ_assoc_get (struct GNUNET_MQ_Handle *mq,
773                      uint32_t request_id)
774 {
775   if (NULL == mq->assoc_map)
776     return NULL;
777   return GNUNET_CONTAINER_multihashmap32_get (mq->assoc_map, request_id);
778 }
779
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_MQ_discard (ev);
881   }
882   if (NULL != mq->current_envelope)
883   {
884     /* we can only discard envelopes that
885      * are not queued! */
886     mq->current_envelope->parent_queue = NULL;
887     GNUNET_MQ_discard (mq->current_envelope);
888     mq->current_envelope = NULL;
889     GNUNET_assert (0 < mq->queue_length);
890     mq->queue_length--;
891   }
892   GNUNET_assert (0 == mq->queue_length);
893   while (NULL != (dnh = mq->dnh_head))
894   {
895     dnh->cb (dnh->cb_cls);
896     GNUNET_MQ_destroy_notify_cancel (dnh);
897   }
898   if (NULL != mq->assoc_map)
899   {
900     GNUNET_CONTAINER_multihashmap32_destroy (mq->assoc_map);
901     mq->assoc_map = NULL;
902   }
903   GNUNET_free_non_null (mq->handlers);
904   GNUNET_free (mq);
905 }
906
907
908 const struct GNUNET_MessageHeader *
909 GNUNET_MQ_extract_nested_mh_ (const struct GNUNET_MessageHeader *mh,
910                               uint16_t base_size)
911 {
912   uint16_t whole_size;
913   uint16_t nested_size;
914   const struct GNUNET_MessageHeader *nested_msg;
915
916   whole_size = ntohs (mh->size);
917   GNUNET_assert (whole_size >= base_size);
918   nested_size = whole_size - base_size;
919   if (0 == nested_size)
920     return NULL;
921   if (nested_size < sizeof (struct GNUNET_MessageHeader))
922   {
923     GNUNET_break_op (0);
924     return NULL;
925   }
926   nested_msg = (const struct GNUNET_MessageHeader *) ((char *) mh + base_size);
927   if (ntohs (nested_msg->size) != nested_size)
928   {
929     GNUNET_break_op (0);
930     return NULL;
931   }
932   return nested_msg;
933 }
934
935
936 /**
937  * Cancel sending the message. Message must have been sent with
938  * #GNUNET_MQ_send before.  May not be called after the notify sent
939  * callback has been called
940  *
941  * @param ev queued envelope to cancel
942  */
943 void
944 GNUNET_MQ_send_cancel (struct GNUNET_MQ_Envelope *ev)
945 {
946   struct GNUNET_MQ_Handle *mq = ev->parent_queue;
947
948   GNUNET_assert (NULL != mq);
949   GNUNET_assert (NULL != mq->cancel_impl);
950
951   mq->evacuate_called = GNUNET_NO;
952
953   if (mq->current_envelope == ev)
954   {
955     /* complex case, we already started with transmitting
956        the message using the callbacks. */
957     GNUNET_assert (0 < mq->queue_length);
958     mq->queue_length--;
959     mq->cancel_impl (mq,
960                      mq->impl_state);
961     /* continue sending the next message, if any */
962     mq->current_envelope = mq->envelope_head;
963     if (NULL != mq->current_envelope)
964     {
965       GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
966                                    mq->envelope_tail,
967                                    mq->current_envelope);
968       mq->send_impl (mq,
969                      mq->current_envelope->mh,
970                      mq->impl_state);
971     }
972   }
973   else
974   {
975     /* simple case, message is still waiting in the queue */
976     GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
977                                  mq->envelope_tail,
978                                  ev);
979     GNUNET_assert (0 < mq->queue_length);
980     mq->queue_length--;
981   }
982
983   if (GNUNET_YES != mq->evacuate_called)
984   {
985     ev->parent_queue = NULL;
986     ev->mh = NULL;
987     /* also frees ev */
988     GNUNET_free (ev);
989   }
990 }
991
992
993 /**
994  * Function to obtain the current envelope
995  * from within #GNUNET_MQ_SendImpl implementations.
996  *
997  * @param mq message queue to interrogate
998  * @return the current envelope
999  */
1000 struct GNUNET_MQ_Envelope *
1001 GNUNET_MQ_get_current_envelope (struct GNUNET_MQ_Handle *mq)
1002 {
1003   return mq->current_envelope;
1004 }
1005
1006
1007 /**
1008  * Function to obtain the last envelope in the queue.
1009  *
1010  * @param mq message queue to interrogate
1011  * @return the last envelope in the queue
1012  */
1013 struct GNUNET_MQ_Envelope *
1014 GNUNET_MQ_get_last_envelope (struct GNUNET_MQ_Handle *mq)
1015 {
1016   if (NULL != mq->envelope_tail)
1017     return mq->envelope_tail;
1018
1019   return mq->current_envelope;
1020 }
1021
1022
1023 /**
1024  * Set application-specific options for this envelope.
1025  * Overrides the options set for the queue with
1026  * #GNUNET_MQ_set_options() for this message only.
1027  *
1028  * @param env message to set options for
1029  * @param flags flags to use (meaning is queue-specific)
1030  * @param extra additional buffer for further data (also queue-specific)
1031  */
1032 void
1033 GNUNET_MQ_env_set_options (struct GNUNET_MQ_Envelope *env,
1034                            uint64_t flags,
1035                            const void *extra)
1036 {
1037   env->flags = flags;
1038   env->extra = extra;
1039   env->have_custom_options = GNUNET_YES;
1040 }
1041
1042
1043 /**
1044  * Get application-specific options for this envelope.
1045  *
1046  * @param env message to set options for
1047  * @param[out] flags set to flags to use (meaning is queue-specific)
1048  * @return extra additional buffer for further data (also queue-specific)
1049  */
1050 const void *
1051 GNUNET_MQ_env_get_options (struct GNUNET_MQ_Envelope *env,
1052                            uint64_t *flags)
1053 {
1054   struct GNUNET_MQ_Handle *mq = env->parent_queue;
1055
1056   if (GNUNET_YES == env->have_custom_options)
1057   {
1058     *flags = env->flags;
1059     return env->extra;
1060   }
1061   if (NULL == mq)
1062   {
1063     *flags = 0;
1064     return NULL;
1065   }
1066   *flags = mq->default_flags;
1067   return mq->default_extra;
1068 }
1069
1070
1071 /**
1072  * Set application-specific options for this queue.
1073  *
1074  * @param mq message queue to set options for
1075  * @param flags flags to use (meaning is queue-specific)
1076  * @param extra additional buffer for further data (also queue-specific)
1077  */
1078 void
1079 GNUNET_MQ_set_options (struct GNUNET_MQ_Handle *mq,
1080                        uint64_t flags,
1081                        const void *extra)
1082 {
1083   mq->default_flags = flags;
1084   mq->default_extra = extra;
1085 }
1086
1087
1088 /**
1089  * Register function to be called whenever @a mq is being
1090  * destroyed.
1091  *
1092  * @param mq message queue to watch
1093  * @param cb function to call on @a mq destruction
1094  * @param cb_cls closure for @a cb
1095  * @return handle for #GNUNET_MQ_destroy_notify_cancel().
1096  */
1097 struct GNUNET_MQ_DestroyNotificationHandle *
1098 GNUNET_MQ_destroy_notify (struct GNUNET_MQ_Handle *mq,
1099                           GNUNET_SCHEDULER_TaskCallback cb,
1100                           void *cb_cls)
1101 {
1102   struct GNUNET_MQ_DestroyNotificationHandle *dnh;
1103
1104   dnh = GNUNET_new (struct GNUNET_MQ_DestroyNotificationHandle);
1105   dnh->mq = mq;
1106   dnh->cb = cb;
1107   dnh->cb_cls = cb_cls;
1108   GNUNET_CONTAINER_DLL_insert (mq->dnh_head,
1109                                mq->dnh_tail,
1110                                dnh);
1111   return dnh;
1112 }
1113
1114
1115 /**
1116  * Cancel registration from #GNUNET_MQ_destroy_notify().
1117  *
1118  * @param dnh handle for registration to cancel
1119  */
1120 void
1121 GNUNET_MQ_destroy_notify_cancel (struct GNUNET_MQ_DestroyNotificationHandle *dnh)
1122 {
1123   struct GNUNET_MQ_Handle *mq = dnh->mq;
1124
1125   GNUNET_CONTAINER_DLL_remove (mq->dnh_head,
1126                                mq->dnh_tail,
1127                                dnh);
1128   GNUNET_free (dnh);
1129 }
1130
1131
1132 /**
1133  * Insert @a env into the envelope DLL starting at @a env_head
1134  * Note that @a env must not be in any MQ while this function
1135  * is used with DLLs defined outside of the MQ module.  This
1136  * is just in case some application needs to also manage a
1137  * FIFO of envelopes independent of MQ itself and wants to
1138  * re-use the pointers internal to @a env.  Use with caution.
1139  *
1140  * @param[in|out] env_head of envelope DLL
1141  * @param[in|out] env_tail tail of envelope DLL
1142  * @param[in|out] env element to insert at the tail
1143  */
1144 void
1145 GNUNET_MQ_dll_insert_tail (struct GNUNET_MQ_Envelope **env_head,
1146                            struct GNUNET_MQ_Envelope **env_tail,
1147                            struct GNUNET_MQ_Envelope *env)
1148 {
1149   GNUNET_CONTAINER_DLL_insert_tail (*env_head,
1150                                     *env_tail,
1151                                     env);
1152 }
1153
1154
1155 /**
1156  * Remove @a env from 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 remove from the DLL
1166  */
1167 void
1168 GNUNET_MQ_dll_remove (struct GNUNET_MQ_Envelope **env_head,
1169                       struct GNUNET_MQ_Envelope **env_tail,
1170                       struct GNUNET_MQ_Envelope *env)
1171 {
1172   GNUNET_CONTAINER_DLL_remove (*env_head,
1173                                *env_tail,
1174                                env);
1175 }
1176
1177
1178 /**
1179  * Copy an array of handlers.
1180  *
1181  * Useful if the array has been delared in local memory and needs to be
1182  * persisted for future use.
1183  *
1184  * @param handlers Array of handlers to be copied. Can be NULL (nothing done).
1185  * @return A newly allocated array of handlers.
1186  *         Needs to be freed with #GNUNET_free.
1187  */
1188 struct GNUNET_MQ_MessageHandler *
1189 GNUNET_MQ_copy_handlers (const struct GNUNET_MQ_MessageHandler *handlers)
1190 {
1191   struct GNUNET_MQ_MessageHandler *copy;
1192   unsigned int count;
1193
1194   if (NULL == handlers)
1195     return NULL;
1196
1197   count = GNUNET_MQ_count_handlers (handlers);
1198   copy = GNUNET_new_array (count + 1,
1199                            struct GNUNET_MQ_MessageHandler);
1200   GNUNET_memcpy (copy,
1201                  handlers,
1202                  count * sizeof (struct GNUNET_MQ_MessageHandler));
1203   return copy;
1204 }
1205
1206
1207 /**
1208  * Count the handlers in a handler array.
1209  *
1210  * @param handlers Array of handlers to be counted.
1211  * @return The number of handlers in the array.
1212  */
1213 unsigned int
1214 GNUNET_MQ_count_handlers (const struct GNUNET_MQ_MessageHandler *handlers)
1215 {
1216   unsigned int i;
1217
1218   if (NULL == handlers)
1219     return 0;
1220
1221   for (i=0; NULL != handlers[i].cb; i++) ;
1222
1223   return i;
1224 }
1225
1226
1227
1228 /* end of mq.c */