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