-remove GNUNET_MQ_impl_send_commit, make it part of send_continue, to ensure calling...
[oweals/gnunet.git] / src / util / mq.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, 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    * usually points to the end of the containing GNUNET_MQ_Envelope
49    */
50   struct GNUNET_MessageHeader *mh;
51
52   /**
53    * Queue the message is queued in, NULL if message is not queued.
54    */
55   struct GNUNET_MQ_Handle *parent_queue;
56
57   /**
58    * Called after the message was sent irrevocably.
59    */
60   GNUNET_MQ_NotifyCallback sent_cb;
61
62   /**
63    * Closure for send_cb
64    */
65   void *sent_cls;
66 };
67
68
69 /**
70  * Handle to a message queue.
71  */
72 struct GNUNET_MQ_Handle
73 {
74   /**
75    * Handlers array, or NULL if the queue should not receive messages
76    */
77   const struct GNUNET_MQ_MessageHandler *handlers;
78
79   /**
80    * Closure for the handler callbacks,
81    * as well as for the error handler.
82    */
83   void *handlers_cls;
84
85   /**
86    * Actual implementation of message sending,
87    * called when a message is added
88    */
89   GNUNET_MQ_SendImpl send_impl;
90
91   /**
92    * Implementation-dependent queue destruction function
93    */
94   GNUNET_MQ_DestroyImpl destroy_impl;
95
96   /**
97    * Implementation-specific state
98    */
99   void *impl_state;
100
101   /**
102    * Callback will be called when an error occurs.
103    */
104   GNUNET_MQ_ErrorHandler error_handler;
105
106   /**
107    * Linked list of messages pending to be sent
108    */
109   struct GNUNET_MQ_Envelope *envelope_head;
110
111   /**
112    * Linked list of messages pending to be sent
113    */
114   struct GNUNET_MQ_Envelope *envelope_tail;
115
116   /**
117    * Message that is currently scheduled to be
118    * sent. Not the head of the message queue, as the implementation
119    * needs to know if sending has been already scheduled or not.
120    */
121   struct GNUNET_MQ_Envelope *current_envelope;
122
123   /**
124    * Map of associations, lazily allocated
125    */
126   struct GNUNET_CONTAINER_MultiHashMap32 *assoc_map;
127
128   /**
129    * Next id that should be used for the assoc_map,
130    * initialized lazily to a random value together with
131    * assoc_map
132    */
133   uint32_t assoc_id;
134 };
135
136
137
138
139 struct ServerClientSocketState
140 {
141   struct GNUNET_SERVER_Client *client;
142   struct GNUNET_SERVER_TransmitHandle* th;
143 };
144
145
146 struct ClientConnectionState
147 {
148   /**
149    * Did we call receive alread alreadyy?
150    */
151   int receive_active;
152
153   /**
154    * Do we also want to receive?
155    */
156   int receive_requested;
157   struct GNUNET_CLIENT_Connection *connection;
158   struct GNUNET_CLIENT_TransmitHandle *th;
159 };
160
161
162 /**
163  * Call the message message handler that was registered
164  * for the type of the given message in the given message queue.
165  *
166  * This function is indended to be used for the implementation
167  * of message queues.
168  *
169  * @param mq message queue with the handlers
170  * @param mh message to dispatch
171  */
172 void
173 GNUNET_MQ_inject_message (struct GNUNET_MQ_Handle *mq, const struct GNUNET_MessageHeader *mh)
174 {
175   const struct GNUNET_MQ_MessageHandler *handler;
176   int handled = GNUNET_NO;
177
178   handler = mq->handlers;
179   if (NULL == handler)
180     return;
181   for (; NULL != handler->cb; handler++)
182   {
183     if (handler->type == ntohs (mh->type))
184     {
185       handler->cb (mq->handlers_cls, mh);
186       handled = GNUNET_YES;
187     }
188   }
189
190   if (GNUNET_NO == handled)
191     LOG (GNUNET_ERROR_TYPE_WARNING, "no handler for message of type %d\n", ntohs (mh->type));
192 }
193
194
195 /**
196  * Call the error handler of a message queue with the given
197  * error code.  If there is no error handler, log a warning.
198  *
199  * This function is intended to be used by the implementation
200  * of message queues.
201  *
202  * @param mq message queue
203  * @param error the error type
204  */
205 void
206 GNUNET_MQ_inject_error (struct GNUNET_MQ_Handle *mq,
207                         enum GNUNET_MQ_Error error)
208 {
209   if (NULL == mq->error_handler)
210   {
211     /* FIXME: log what kind of error occured */
212     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "mq: got error, but no handler installed\n");
213     return;
214   }
215   mq->error_handler (mq->handlers_cls, error);
216 }
217
218
219 void
220 GNUNET_MQ_discard (struct GNUNET_MQ_Envelope *mqm)
221 {
222   GNUNET_assert (NULL == mqm->parent_queue);
223   GNUNET_free (mqm);
224 }
225
226
227 /**
228  * Send a message with the give message queue.
229  * May only be called once per message.
230  *
231  * @param mq message queue
232  * @param ev the envelope with the message to send.
233  */
234 void
235 GNUNET_MQ_send (struct GNUNET_MQ_Handle *mq, struct GNUNET_MQ_Envelope *ev)
236 {
237   GNUNET_assert (NULL != mq);
238   GNUNET_assert (NULL == ev->parent_queue);
239
240   /* is the implementation busy? queue it! */
241   if (NULL != mq->current_envelope)
242   {
243     GNUNET_CONTAINER_DLL_insert_tail (mq->envelope_head, mq->envelope_tail, ev);
244     return;
245   }
246   mq->current_envelope = ev;
247   mq->send_impl (mq, ev->mh, mq->impl_state);
248 }
249
250
251 /**
252  * Call the send implementation for the next queued message,
253  * if any.
254  * Only useful for implementing message queues,
255  * results in undefined behavior if not used carefully.
256  *
257  * @param mq message queue to send the next message with
258  */
259 void
260 GNUNET_MQ_impl_send_continue (struct GNUNET_MQ_Handle *mq)
261 {
262   struct GNUNET_MQ_Envelope *current_envelope;
263
264   /* call is only valid if we're actually currently sending
265    * a message */
266   current_envelope = mq->current_envelope;
267   GNUNET_assert (NULL != current_envelope);
268   if (NULL == mq->envelope_head)
269   {
270     mq->current_envelope = NULL;
271   }
272   else
273   {
274     mq->current_envelope = mq->envelope_head;
275     GNUNET_CONTAINER_DLL_remove (mq->envelope_head,
276                                  mq->envelope_tail,
277                                  mq->current_envelope);
278     mq->send_impl (mq, mq->current_envelope->mh, mq->impl_state);
279   }
280   if (NULL != current_envelope->sent_cb)
281     current_envelope->sent_cb (current_envelope->sent_cls);
282   GNUNET_free (current_envelope);
283 }
284
285
286 /**
287  * Create a message queue for the specified handlers.
288  *
289  * @param send function the implements sending messages
290  * @param destroy function that implements destroying the queue
291  * @param cancel function that implements canceling a message
292  * @param impl_state for the queue, passed to 'send' and 'destroy'
293  * @param handlers array of message handlers
294  * @param error_handler handler for read and write errors
295  * @param cls closure for message handlers and error handler
296  * @return a new message queue
297  */
298 struct GNUNET_MQ_Handle *
299 GNUNET_MQ_queue_for_callbacks (GNUNET_MQ_SendImpl send,
300                                GNUNET_MQ_DestroyImpl destroy,
301                                GNUNET_MQ_CancelImpl cancel,
302                                void *impl_state,
303                                const struct GNUNET_MQ_MessageHandler *handlers,
304                                GNUNET_MQ_ErrorHandler error_handler,
305                                void *cls)
306 {
307   struct GNUNET_MQ_Handle *mq;
308
309   mq = GNUNET_new (struct GNUNET_MQ_Handle);
310   mq->send_impl = send;
311   mq->destroy_impl = destroy;
312   mq->handlers = handlers;
313   mq->handlers_cls = cls;
314   mq->impl_state = impl_state;
315
316   return mq;
317 }
318
319
320 /**
321  * Get the message that should currently be sent.
322  * Fails if there is no current message.
323  * Only useful for implementing message queues,
324  * results in undefined behavior if not used carefully.
325  *
326  * @param mq message queue with the current message
327  * @return message to send, never NULL
328  */
329 const struct GNUNET_MessageHeader *
330 GNUNET_MQ_impl_current (struct GNUNET_MQ_Handle *mq)
331 {
332   if (NULL == mq->current_envelope)
333     GNUNET_abort ();
334   if (NULL == mq->current_envelope->mh)
335     GNUNET_abort ();
336   return mq->current_envelope->mh;
337 }
338
339
340 /**
341  * Get the implementation state associated with the
342  * message queue.
343  *
344  * While the GNUNET_MQ_Impl* callbacks receive the
345  * implementation state, continuations that are scheduled
346  * by the implementation function often only have one closure
347  * argument, with this function it is possible to get at the
348  * implementation state when only passing the GNUNET_MQ_Handle
349  * as closure.
350  *
351  * @param mq message queue with the current message
352  * @return message to send, never NULL
353  */
354 void *
355 GNUNET_MQ_impl_state (struct GNUNET_MQ_Handle *mq)
356 {
357   return mq->impl_state;
358 }
359
360
361 struct GNUNET_MQ_Envelope *
362 GNUNET_MQ_msg_ (struct GNUNET_MessageHeader **mhp, uint16_t size, uint16_t type)
363 {
364   struct GNUNET_MQ_Envelope *mqm;
365
366   mqm = GNUNET_malloc (sizeof *mqm + size);
367   mqm->mh = (struct GNUNET_MessageHeader *) &mqm[1];
368   mqm->mh->size = htons (size);
369   mqm->mh->type = htons (type);
370   if (NULL != mhp)
371     *mhp = mqm->mh;
372   return mqm;
373 }
374
375
376 /**
377  * Implementation of the GNUNET_MQ_msg_nested_mh macro.
378  *
379  * @param mhp pointer to the message header pointer that will be changed to allocate at
380  *        the newly allocated space for the message.
381  * @param base_size size of the data before the nested message
382  * @param type type of the message in the envelope
383  * @param nested_mh the message to append to the message after base_size
384  */
385 struct GNUNET_MQ_Envelope *
386 GNUNET_MQ_msg_nested_mh_ (struct GNUNET_MessageHeader **mhp, uint16_t base_size, uint16_t type,
387                           const struct GNUNET_MessageHeader *nested_mh)
388 {
389   struct GNUNET_MQ_Envelope *mqm;
390   uint16_t size;
391
392   if (NULL == nested_mh)
393     return GNUNET_MQ_msg_ (mhp, base_size, type);
394
395   size = base_size + ntohs (nested_mh->size);
396
397   /* check for uint16_t overflow */
398   if (size < base_size)
399     return NULL;
400
401   mqm = GNUNET_MQ_msg_ (mhp, size, type);
402   memcpy ((char *) mqm->mh + base_size, nested_mh, ntohs (nested_mh->size));
403
404   return mqm;
405 }
406
407
408 /**
409  * Transmit a queued message to the session's client.
410  *
411  * @param cls consensus session
412  * @param size number of bytes available in buf
413  * @param buf where the callee should write the message
414  * @return number of bytes written to buf
415  */
416 static size_t
417 transmit_queued (void *cls, size_t size,
418                  void *buf)
419 {
420   struct GNUNET_MQ_Handle *mq = cls;
421   struct ServerClientSocketState *state = GNUNET_MQ_impl_state (mq);
422   const struct GNUNET_MessageHeader *msg = GNUNET_MQ_impl_current (mq);
423   size_t msg_size;
424
425   GNUNET_assert (NULL != buf);
426
427   msg_size = ntohs (msg->size);
428   GNUNET_assert (size >= msg_size);
429   memcpy (buf, msg, msg_size);
430   state->th = NULL;
431
432   GNUNET_MQ_impl_send_continue (mq);
433
434   return msg_size;
435 }
436
437
438
439 static void
440 server_client_destroy_impl (struct GNUNET_MQ_Handle *mq,
441                             void *impl_state)
442 {
443   struct ServerClientSocketState *state = impl_state;
444
445   GNUNET_assert (NULL != mq);
446   GNUNET_assert (NULL != state);
447   GNUNET_SERVER_client_drop (state->client);
448   GNUNET_free (state);
449 }
450
451 static void
452 server_client_send_impl (struct GNUNET_MQ_Handle *mq,
453                          const struct GNUNET_MessageHeader *msg, void *impl_state)
454 {
455   struct ServerClientSocketState *state = impl_state;
456
457   GNUNET_assert (NULL != mq);
458   GNUNET_assert (NULL != state);
459   state->th =
460       GNUNET_SERVER_notify_transmit_ready (state->client, ntohs (msg->size),
461                                            GNUNET_TIME_UNIT_FOREVER_REL,
462                                            &transmit_queued, mq);
463 }
464
465
466 struct GNUNET_MQ_Handle *
467 GNUNET_MQ_queue_for_server_client (struct GNUNET_SERVER_Client *client)
468 {
469   struct GNUNET_MQ_Handle *mq;
470   struct ServerClientSocketState *scss;
471
472   mq = GNUNET_new (struct GNUNET_MQ_Handle);
473   scss = GNUNET_new (struct ServerClientSocketState);
474   mq->impl_state = scss;
475   scss->client = client;
476   GNUNET_SERVER_client_keep (client);
477   mq->send_impl = server_client_send_impl;
478   mq->destroy_impl = server_client_destroy_impl;
479   return mq;
480 }
481
482
483 /**
484  * Type of a function to call when we receive a message
485  * from the service.
486  *
487  * @param cls closure
488  * @param msg message received, NULL on timeout or fatal error
489  */
490 static void
491 handle_client_message (void *cls,
492                        const struct GNUNET_MessageHeader *msg)
493 {
494   struct GNUNET_MQ_Handle *mq = cls;
495   struct ClientConnectionState *state;
496
497   state = mq->impl_state;
498
499   if (NULL == msg)
500   {
501     GNUNET_MQ_inject_error (mq, GNUNET_MQ_ERROR_READ);
502     return;
503   }
504
505   GNUNET_CLIENT_receive (state->connection, handle_client_message, mq,
506                          GNUNET_TIME_UNIT_FOREVER_REL);
507
508   GNUNET_MQ_inject_message (mq, msg);
509 }
510
511
512 /**
513  * Transmit a queued message to the session's client.
514  *
515  * @param cls consensus session
516  * @param size number of bytes available in buf
517  * @param buf where the callee should write the message
518  * @return number of bytes written to buf
519  */
520 static size_t
521 connection_client_transmit_queued (void *cls, size_t size,
522                  void *buf)
523 {
524   struct GNUNET_MQ_Handle *mq = cls;
525   const struct GNUNET_MessageHeader *msg;
526   struct ClientConnectionState *state = mq->impl_state;
527   size_t msg_size;
528
529   GNUNET_assert (NULL != mq);
530   msg = GNUNET_MQ_impl_current (mq);
531
532   if (NULL == buf)
533   {
534     GNUNET_MQ_inject_error (mq, GNUNET_MQ_ERROR_READ);
535     return 0;
536   }
537
538   if ( (GNUNET_YES == state->receive_requested) &&
539        (GNUNET_NO == state->receive_active) )
540   {
541     state->receive_active = GNUNET_YES;
542     GNUNET_CLIENT_receive (state->connection, handle_client_message, mq,
543                            GNUNET_TIME_UNIT_FOREVER_REL);
544   }
545
546
547   msg_size = ntohs (msg->size);
548   GNUNET_assert (size >= msg_size);
549   memcpy (buf, msg, msg_size);
550   state->th = NULL;
551
552   GNUNET_MQ_impl_send_continue (mq);
553
554   return msg_size;
555 }
556
557
558
559 static void
560 connection_client_destroy_impl (struct GNUNET_MQ_Handle *mq, void *impl_state)
561 {
562   GNUNET_free (impl_state);
563 }
564
565 static void
566 connection_client_send_impl (struct GNUNET_MQ_Handle *mq,
567                              const struct GNUNET_MessageHeader *msg, void *impl_state)
568 {
569   struct ClientConnectionState *state = impl_state;
570
571   GNUNET_assert (NULL != state);
572   GNUNET_assert (NULL == state->th);
573   state->th =
574       GNUNET_CLIENT_notify_transmit_ready (state->connection, ntohs (msg->size),
575                                            GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_NO,
576                                            &connection_client_transmit_queued, mq);
577   GNUNET_assert (NULL != state->th);
578 }
579
580
581 struct GNUNET_MQ_Handle *
582 GNUNET_MQ_queue_for_connection_client (struct GNUNET_CLIENT_Connection *connection,
583                                        const struct GNUNET_MQ_MessageHandler *handlers,
584                                        GNUNET_MQ_ErrorHandler error_handler,
585                                        void *cls)
586 {
587   struct GNUNET_MQ_Handle *mq;
588   struct ClientConnectionState *state;
589
590   GNUNET_assert (NULL != connection);
591
592   mq = GNUNET_new (struct GNUNET_MQ_Handle);
593   mq->handlers = handlers;
594   mq->error_handler = error_handler;
595   mq->handlers_cls = cls;
596   state = GNUNET_new (struct ClientConnectionState);
597   state->connection = connection;
598   mq->impl_state = state;
599   mq->send_impl = connection_client_send_impl;
600   mq->destroy_impl = connection_client_destroy_impl;
601   if (NULL != handlers)
602     state->receive_requested = GNUNET_YES;
603
604   return mq;
605 }
606
607
608 void
609 GNUNET_MQ_replace_handlers (struct GNUNET_MQ_Handle *mq,
610                             const struct GNUNET_MQ_MessageHandler *new_handlers,
611                             void *cls)
612 {
613   /* FIXME: notify implementation? */
614   /* FIXME: what about NULL handlers? abort receive? */
615   mq->handlers = new_handlers;
616   mq->handlers_cls = cls;
617 }
618
619
620 /**
621  * Associate the assoc_data in mq with a unique request id.
622  *
623  * @param mq message queue, id will be unique for the queue
624  * @param assoc_data to associate
625  */
626 uint32_t
627 GNUNET_MQ_assoc_add (struct GNUNET_MQ_Handle *mq,
628                      void *assoc_data)
629 {
630   uint32_t id;
631
632   if (NULL == mq->assoc_map)
633   {
634     mq->assoc_map = GNUNET_CONTAINER_multihashmap32_create (8);
635     mq->assoc_id = 1;
636   }
637   id = mq->assoc_id++;
638   GNUNET_CONTAINER_multihashmap32_put (mq->assoc_map, id, assoc_data,
639                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
640   return id;
641 }
642
643
644
645 void *
646 GNUNET_MQ_assoc_get (struct GNUNET_MQ_Handle *mq, uint32_t request_id)
647 {
648   if (NULL == mq->assoc_map)
649     return NULL;
650   return GNUNET_CONTAINER_multihashmap32_get (mq->assoc_map, request_id);
651 }
652
653
654 void *
655 GNUNET_MQ_assoc_remove (struct GNUNET_MQ_Handle *mq, uint32_t request_id)
656 {
657   void *val;
658
659   if (NULL == mq->assoc_map)
660     return NULL;
661   val = GNUNET_CONTAINER_multihashmap32_get (mq->assoc_map, request_id);
662   GNUNET_CONTAINER_multihashmap32_remove_all (mq->assoc_map, request_id);
663   return val;
664 }
665
666
667 void
668 GNUNET_MQ_notify_sent (struct GNUNET_MQ_Envelope *mqm,
669                        GNUNET_MQ_NotifyCallback cb,
670                        void *cls)
671 {
672   mqm->sent_cb = cb;
673   mqm->sent_cls = cls;
674 }
675
676
677 void
678 GNUNET_MQ_destroy (struct GNUNET_MQ_Handle *mq)
679 {
680   if (NULL != mq->destroy_impl)
681   {
682     mq->destroy_impl (mq, mq->impl_state);
683   }
684
685   while (NULL != mq->envelope_head)
686   {
687     struct GNUNET_MQ_Envelope *ev;
688     ev = mq->envelope_head;
689     GNUNET_CONTAINER_DLL_remove (mq->envelope_head, mq->envelope_tail, ev);
690     GNUNET_MQ_discard (ev);
691   }
692
693   if (NULL != mq->current_envelope)
694   {
695     GNUNET_MQ_discard (mq->current_envelope);
696     mq->current_envelope = NULL;
697   }
698
699   if (NULL != mq->assoc_map)
700   {
701     GNUNET_CONTAINER_multihashmap32_destroy (mq->assoc_map);
702     mq->assoc_map = NULL;
703   }
704
705   GNUNET_free (mq);
706 }
707
708
709 struct GNUNET_MessageHeader *
710 GNUNET_MQ_extract_nested_mh_ (const struct GNUNET_MessageHeader *mh, uint16_t base_size)
711 {
712   uint16_t whole_size;
713   uint16_t nested_size;
714   struct GNUNET_MessageHeader *nested_msg;
715
716   whole_size = ntohs (mh->size);
717   GNUNET_assert (whole_size >= base_size);
718
719   nested_size = whole_size - base_size;
720
721   if (0 == nested_size)
722     return NULL;
723
724   if (nested_size < sizeof (struct GNUNET_MessageHeader))
725   {
726     GNUNET_break_op (0);
727     return NULL;
728   }
729
730   nested_msg = (struct GNUNET_MessageHeader *) ((char *) mh + base_size);
731
732   if (ntohs (nested_msg->size) != nested_size)
733   {
734     GNUNET_break_op (0);
735     nested_msg->size = htons (nested_size);
736   }
737
738   return nested_msg;
739 }
740
741