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