- another fix to generation handling and lazy copying
[oweals/gnunet.git] / src / set / gnunet-service-set.c
1 /*
2       This file is part of GNUnet
3       Copyright (C) 2013, 2014 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., 51 Franklin Street, Fifth Floor,
18       Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file set/gnunet-service-set.c
22  * @brief two-peer set operations
23  * @author Florian Dold
24  * @author Christian Grothoff
25  */
26 #include "gnunet-service-set.h"
27 #include "gnunet-service-set_protocol.h"
28
29 /**
30  * How long do we hold on to an incoming channel if there is
31  * no local listener before giving up?
32  */
33 #define INCOMING_CHANNEL_TIMEOUT GNUNET_TIME_UNIT_MINUTES
34
35 /**
36  * A listener is inhabited by a client, and waits for evaluation
37  * requests from remote peers.
38  */
39 struct Listener
40 {
41   /**
42    * Listeners are held in a doubly linked list.
43    */
44   struct Listener *next;
45
46   /**
47    * Listeners are held in a doubly linked list.
48    */
49   struct Listener *prev;
50
51   /**
52    * Client that owns the listener.
53    * Only one client may own a listener.
54    */
55   struct GNUNET_SERVER_Client *client;
56
57   /**
58    * Message queue for the client
59    */
60   struct GNUNET_MQ_Handle *client_mq;
61
62   /**
63    * Application ID for the operation, used to distinguish
64    * multiple operations of the same type with the same peer.
65    */
66   struct GNUNET_HashCode app_id;
67
68   /**
69    * The type of the operation.
70    */
71   enum GNUNET_SET_OperationType operation;
72 };
73
74
75 struct LazyCopyRequest
76 {
77   struct Set *source_set;
78   uint32_t cookie;
79
80   struct LazyCopyRequest *prev;
81   struct LazyCopyRequest *next;
82 };
83
84
85 /**
86  * Configuration of our local peer.
87  */
88 static const struct GNUNET_CONFIGURATION_Handle *configuration;
89
90 /**
91  * Handle to the cadet service, used to listen for and connect to
92  * remote peers.
93  */
94 static struct GNUNET_CADET_Handle *cadet;
95
96 /**
97  * Sets are held in a doubly linked list.
98  */
99 static struct Set *sets_head;
100
101 /**
102  * Sets are held in a doubly linked list.
103  */
104 static struct Set *sets_tail;
105
106 /**
107  * Listeners are held in a doubly linked list.
108  */
109 static struct Listener *listeners_head;
110
111 /**
112  * Listeners are held in a doubly linked list.
113  */
114 static struct Listener *listeners_tail;
115
116 /**
117  * Incoming sockets from remote peers are held in a doubly linked
118  * list.
119  */
120 static struct Operation *incoming_head;
121
122 /**
123  * Incoming sockets from remote peers are held in a doubly linked
124  * list.
125  */
126 static struct Operation *incoming_tail;
127
128 static struct LazyCopyRequest *lazy_copy_head;
129 static struct LazyCopyRequest *lazy_copy_tail;
130
131 static uint32_t lazy_copy_cookie = 1;
132
133 /**
134  * Counter for allocating unique IDs for clients, used to identify
135  * incoming operation requests from remote peers, that the client can
136  * choose to accept or refuse.
137  */
138 static uint32_t suggest_id = 1;
139
140
141 /**
142  * Get set that is owned by the given client, if any.
143  *
144  * @param client client to look for
145  * @return set that the client owns, NULL if the client
146  *         does not own a set
147  */
148 static struct Set *
149 set_get (struct GNUNET_SERVER_Client *client)
150 {
151   struct Set *set;
152
153   for (set = sets_head; NULL != set; set = set->next)
154     if (set->client == client)
155       return set;
156   return NULL;
157 }
158
159
160 /**
161  * Get the listener associated with the given client, if any.
162  *
163  * @param client the client
164  * @return listener associated with the client, NULL
165  *         if there isn't any
166  */
167 static struct Listener *
168 listener_get (struct GNUNET_SERVER_Client *client)
169 {
170   struct Listener *listener;
171
172   for (listener = listeners_head; NULL != listener; listener = listener->next)
173     if (listener->client == client)
174       return listener;
175   return NULL;
176 }
177
178
179 /**
180  * Get the incoming socket associated with the given id.
181  *
182  * @param id id to look for
183  * @return the incoming socket associated with the id,
184  *         or NULL if there is none
185  */
186 static struct Operation *
187 get_incoming (uint32_t id)
188 {
189   struct Operation *op;
190
191   for (op = incoming_head; NULL != op; op = op->next)
192     if (op->suggest_id == id)
193     {
194       GNUNET_assert (GNUNET_YES == op->is_incoming);
195       return op;
196     }
197   return NULL;
198 }
199
200
201 /**
202  * Destroy a listener, free all resources associated with it.
203  *
204  * @param listener listener to destroy
205  */
206 static void
207 listener_destroy (struct Listener *listener)
208 {
209   /* If the client is not dead yet, destroy it.
210    * The client's destroy callback will destroy the listener again. */
211   if (NULL != listener->client)
212   {
213     struct GNUNET_SERVER_Client *client = listener->client;
214
215     listener->client = NULL;
216     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
217                 "Disconnecting listener client\n");
218     GNUNET_SERVER_client_disconnect (client);
219     return;
220   }
221   if (NULL != listener->client_mq)
222   {
223     GNUNET_MQ_destroy (listener->client_mq);
224     listener->client_mq = NULL;
225   }
226   GNUNET_CONTAINER_DLL_remove (listeners_head,
227                                listeners_tail,
228                                listener);
229   GNUNET_free (listener);
230 }
231
232
233 /**
234  * Context for the #garbage_collect_cb().
235  */
236 struct GarbageContext
237 {
238
239   /**
240    * Map for which we are garbage collecting removed elements.
241    */
242   struct GNUNET_CONTAINER_MultiHashMap *map;
243
244   /**
245    * Lowest generation for which an operation is still pending.
246    */
247   unsigned int min_op_generation;
248
249   /**
250    * Largest generation for which an operation is still pending.
251    */
252   unsigned int max_op_generation;
253
254 };
255
256
257 /**
258  * Function invoked to check if an element can be removed from
259  * the set's history because it is no longer needed.
260  *
261  * @param cls the `struct GarbageContext *`
262  * @param key key of the element in the map
263  * @param value the `struct ElementEntry *`
264  * @return #GNUNET_OK (continue to iterate)
265  */
266 static int
267 garbage_collect_cb (void *cls,
268                     const struct GNUNET_HashCode *key,
269                     void *value)
270 {
271   //struct GarbageContext *gc = cls;
272   //struct ElementEntry *ee = value;
273
274   //if (GNUNET_YES != ee->removed)
275   //  return GNUNET_OK;
276   //if ( (gc->max_op_generation < ee->generation_added) ||
277   //     (ee->generation_removed > gc->min_op_generation) )
278   //{
279   //  GNUNET_assert (GNUNET_YES ==
280   //                 GNUNET_CONTAINER_multihashmap_remove (gc->map,
281   //                                                       key,
282   //                                                       ee));
283   //  GNUNET_free (ee);
284   //}
285   return GNUNET_OK;
286 }
287
288
289 /**
290  * Collect and destroy elements that are not needed anymore, because
291  * their lifetime (as determined by their generation) does not overlap
292  * with any active set operation.
293  *
294  * @param set set to garbage collect
295  */
296 static void
297 collect_generation_garbage (struct Set *set)
298 {
299   struct Operation *op;
300   struct GarbageContext gc;
301
302   gc.min_op_generation = UINT_MAX;
303   gc.max_op_generation = 0;
304   for (op = set->ops_head; NULL != op; op = op->next)
305   {
306     gc.min_op_generation = GNUNET_MIN (gc.min_op_generation,
307                                        op->generation_created);
308     gc.max_op_generation = GNUNET_MAX (gc.max_op_generation,
309                                        op->generation_created);
310   }
311   gc.map = set->content->elements;
312   GNUNET_CONTAINER_multihashmap_iterate (set->content->elements,
313                                          &garbage_collect_cb,
314                                          &gc);
315 }
316
317 int
318 is_excluded_generation (unsigned int generation,
319                         struct GenerationRange *excluded,
320                         unsigned int excluded_size)
321 {
322   unsigned int i;
323
324   for (i = 0; i < excluded_size; i++)
325   {
326     if ( (generation >= excluded[i].start) && (generation < excluded[i].end) )
327       return GNUNET_YES;
328   }
329
330   return GNUNET_NO;
331 }
332
333
334 int
335 is_element_of_generation (struct ElementEntry *ee,
336                           unsigned int query_generation,
337                           struct GenerationRange *excluded,
338                           unsigned int excluded_size)
339 {
340   struct MutationEvent *mut;
341   int is_present;
342   unsigned int i;
343
344   GNUNET_assert (NULL != ee->mutations);
345
346   if (GNUNET_YES == is_excluded_generation (query_generation, excluded, excluded_size))
347   {
348     GNUNET_break (0);
349     return GNUNET_NO;
350   }
351
352   is_present = GNUNET_NO;
353
354   /* Could be made faster with binary search, but lists
355      are small, so why bother. */
356   for (i = 0; i < ee->mutations_size; i++)
357   {
358     mut = &ee->mutations[i];
359
360     if (mut->generation > query_generation)
361     {
362       /* The mutation doesn't apply to our generation
363          anymore.  We can'b break here, since mutations aren't
364          sorted by generation. */
365       continue;
366     }
367
368     if (GNUNET_YES == is_excluded_generation (mut->generation, excluded, excluded_size))
369     {
370       /* The generation is excluded (because it belongs to another
371          fork via a lazy copy) and thus mutations aren't considered
372          for membership testing. */
373       continue;
374     }
375
376     /* This would be an inconsistency in how we manage mutations. */
377     if ( (GNUNET_YES == is_present) && (GNUNET_YES == mut->added) )
378       GNUNET_assert (0);
379
380     /* Likewise. */
381     if ( (GNUNET_NO == is_present) && (GNUNET_NO == mut->added) )
382       GNUNET_assert (0);
383
384     is_present = mut->added;
385   }
386
387   return is_present;
388 }
389
390
391 int
392 _GSS_is_element_of_set (struct ElementEntry *ee,
393                         struct Set *set)
394 {
395   return is_element_of_generation (ee,
396                                    set->current_generation,
397                                    set->excluded_generations,
398                                    set->excluded_generations_size);
399 }
400
401
402 static int
403 is_element_of_iteration (struct ElementEntry *ee,
404                          struct Set *set)
405 {
406   return is_element_of_generation (ee,
407                                    set->iter_generation,
408                                    set->excluded_generations,
409                                    set->excluded_generations_size);
410 }
411
412
413 int
414 _GSS_is_element_of_operation (struct ElementEntry *ee,
415                               struct Operation *op)
416 {
417   return is_element_of_generation (ee,
418                                    op->generation_created,
419                                    op->spec->set->excluded_generations,
420                                    op->spec->set->excluded_generations_size);
421 }
422
423
424 /**
425  * Destroy the given operation.  Call the implementation-specific
426  * cancel function of the operation.  Disconnects from the remote
427  * peer.  Does not disconnect the client, as there may be multiple
428  * operations per set.
429  *
430  * @param op operation to destroy
431  * @param gc #GNUNET_YES to perform garbage collection on the set
432  */
433 void
434 _GSS_operation_destroy (struct Operation *op,
435                         int gc)
436 {
437   struct Set *set;
438   struct GNUNET_CADET_Channel *channel;
439
440   if (NULL == op->vt)
441   {
442     /* already in #_GSS_operation_destroy() */
443     return;
444   }
445   GNUNET_assert (GNUNET_NO == op->is_incoming);
446   GNUNET_assert (NULL != op->spec);
447   set = op->spec->set;
448   GNUNET_CONTAINER_DLL_remove (set->ops_head,
449                                set->ops_tail,
450                                op);
451   op->vt->cancel (op);
452   op->vt = NULL;
453   if (NULL != op->spec)
454   {
455     if (NULL != op->spec->context_msg)
456     {
457       GNUNET_free (op->spec->context_msg);
458       op->spec->context_msg = NULL;
459     }
460     GNUNET_free (op->spec);
461     op->spec = NULL;
462   }
463   if (NULL != op->mq)
464   {
465     GNUNET_MQ_destroy (op->mq);
466     op->mq = NULL;
467   }
468   if (NULL != (channel = op->channel))
469   {
470     op->channel = NULL;
471     GNUNET_CADET_channel_destroy (channel);
472   }
473   if (GNUNET_YES == gc)
474     collect_generation_garbage (set);
475   /* We rely on the channel end handler to free 'op'. When 'op->channel' was NULL,
476    * there was a channel end handler that will free 'op' on the call stack. */
477 }
478
479
480 /**
481  * Iterator over hash map entries to free element entries.
482  *
483  * @param cls closure
484  * @param key current key code
485  * @param value a `struct ElementEntry *` to be free'd
486  * @return #GNUNET_YES (continue to iterate)
487  */
488 static int
489 destroy_elements_iterator (void *cls,
490                            const struct GNUNET_HashCode *key,
491                            void *value)
492 {
493   struct ElementEntry *ee = value;
494
495   GNUNET_free_non_null (ee->mutations);
496
497   GNUNET_free (ee);
498   return GNUNET_YES;
499 }
500
501
502 /**
503  * Destroy a set, and free all resources and operations associated with it.
504  *
505  * @param set the set to destroy
506  */
507 static void
508 set_destroy (struct Set *set)
509 {
510   if (NULL != set->client)
511   {
512     /* If the client is not dead yet, destroy it.  The client's destroy
513      * callback will call `set_destroy()` again in this case.  We do
514      * this so that the channel end handler still has a valid set handle
515      * to destroy. */
516     struct GNUNET_SERVER_Client *client = set->client;
517
518     set->client = NULL;
519     GNUNET_SERVER_client_disconnect (client);
520     return;
521   }
522   GNUNET_assert (NULL != set->state);
523   while (NULL != set->ops_head)
524     _GSS_operation_destroy (set->ops_head, GNUNET_NO);
525   set->vt->destroy_set (set->state);
526   set->state = NULL;
527   if (NULL != set->client_mq)
528   {
529     GNUNET_MQ_destroy (set->client_mq);
530     set->client_mq = NULL;
531   }
532   if (NULL != set->iter)
533   {
534     GNUNET_CONTAINER_multihashmap_iterator_destroy (set->iter);
535     set->iter = NULL;
536     set->iteration_id++;
537   }
538   {
539     struct SetContent *content;
540     struct PendingMutation *pm;
541     struct PendingMutation *pm_current;
542
543     content = set->content;
544
545     // discard any pending mutations that reference this set
546     pm = content->pending_mutations_head;
547     while (NULL != pm)
548     {
549       pm_current = pm;
550       pm = pm->next;
551       if (pm_current-> set == set)
552         GNUNET_CONTAINER_DLL_remove (content->pending_mutations_head,
553                                      content->pending_mutations_tail,
554                                      pm_current);
555
556     }
557
558     set->content = NULL;
559     GNUNET_assert (0 != content->refcount);
560     content->refcount -= 1;
561     if (0 == content->refcount)
562     {
563       GNUNET_assert (NULL != content->elements);
564       GNUNET_CONTAINER_multihashmap_iterate (content->elements,
565                                              &destroy_elements_iterator,
566                                              NULL);
567       GNUNET_CONTAINER_multihashmap_destroy (content->elements);
568       content->elements = NULL;
569       GNUNET_free (content);
570     }
571   }
572   GNUNET_free_non_null (set->excluded_generations);
573   set->excluded_generations = NULL;
574   GNUNET_CONTAINER_DLL_remove (sets_head,
575                                sets_tail,
576                                set);
577
578   // remove set from pending copy requests
579   {
580     struct LazyCopyRequest *lcr;
581     lcr = lazy_copy_head;
582     while (NULL != lcr)
583     {
584       struct LazyCopyRequest *lcr_current;
585       lcr_current = lcr;
586       lcr = lcr->next;
587       if (lcr_current->source_set == set)
588         GNUNET_CONTAINER_DLL_remove (lazy_copy_head,
589                                      lazy_copy_tail,
590                                      lcr_current);
591     }
592   }
593
594   GNUNET_free (set);
595 }
596
597
598 /**
599  * Clean up after a client has disconnected
600  *
601  * @param cls closure, unused
602  * @param client the client to clean up after
603  */
604 static void
605 handle_client_disconnect (void *cls,
606                           struct GNUNET_SERVER_Client *client)
607 {
608   struct Set *set;
609   struct Listener *listener;
610
611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
612               "client disconnected, cleaning up\n");
613   set = set_get (client);
614   if (NULL != set)
615   {
616     set->client = NULL;
617     set_destroy (set);
618     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
619                 "Client's set destroyed\n");
620   }
621   listener = listener_get (client);
622   if (NULL != listener)
623   {
624     listener->client = NULL;
625     listener_destroy (listener);
626     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
627                 "Client's listener destroyed\n");
628   }
629 }
630
631
632 /**
633  * Destroy an incoming request from a remote peer
634  *
635  * @param incoming remote request to destroy
636  */
637 static void
638 incoming_destroy (struct Operation *incoming)
639 {
640   struct GNUNET_CADET_Channel *channel;
641
642   GNUNET_assert (GNUNET_YES == incoming->is_incoming);
643   GNUNET_CONTAINER_DLL_remove (incoming_head,
644                                incoming_tail,
645                                incoming);
646   if (NULL != incoming->timeout_task)
647   {
648     GNUNET_SCHEDULER_cancel (incoming->timeout_task);
649     incoming->timeout_task = NULL;
650   }
651   /* make sure that the tunnel end handler will not destroy us again */
652   incoming->vt = NULL;
653   if (NULL != incoming->spec)
654   {
655     GNUNET_free (incoming->spec);
656     incoming->spec = NULL;
657   }
658   if (NULL != incoming->mq)
659   {
660     GNUNET_MQ_destroy (incoming->mq);
661     incoming->mq = NULL;
662   }
663   if (NULL != (channel = incoming->channel))
664   {
665     incoming->channel = NULL;
666     GNUNET_CADET_channel_destroy (channel);
667   }
668 }
669
670
671 /**
672  * Find a listener that is interested in the given operation type
673  * and application id.
674  *
675  * @param op operation type to look for
676  * @param app_id application id to look for
677  * @return a matching listener, or NULL if no listener matches the
678  *         given operation and application id
679  */
680 static struct Listener *
681 listener_get_by_target (enum GNUNET_SET_OperationType op,
682                         const struct GNUNET_HashCode *app_id)
683 {
684   struct Listener *listener;
685
686   for (listener = listeners_head; NULL != listener; listener = listener->next)
687     if ( (listener->operation == op) &&
688          (0 == GNUNET_CRYPTO_hash_cmp (app_id, &listener->app_id)) )
689       return listener;
690   return NULL;
691 }
692
693
694 /**
695  * Suggest the given request to the listener. The listening client can
696  * then accept or reject the remote request.
697  *
698  * @param incoming the incoming peer with the request to suggest
699  * @param listener the listener to suggest the request to
700  */
701 static void
702 incoming_suggest (struct Operation *incoming,
703                   struct Listener *listener)
704 {
705   struct GNUNET_MQ_Envelope *mqm;
706   struct GNUNET_SET_RequestMessage *cmsg;
707
708   GNUNET_assert (GNUNET_YES == incoming->is_incoming);
709   GNUNET_assert (NULL != incoming->spec);
710   GNUNET_assert (0 == incoming->suggest_id);
711   incoming->suggest_id = suggest_id++;
712   if (0 == suggest_id)
713     suggest_id++;
714   GNUNET_assert (NULL != incoming->timeout_task);
715   GNUNET_SCHEDULER_cancel (incoming->timeout_task);
716   incoming->timeout_task = NULL;
717   mqm = GNUNET_MQ_msg_nested_mh (cmsg,
718                                  GNUNET_MESSAGE_TYPE_SET_REQUEST,
719                                  incoming->spec->context_msg);
720   GNUNET_assert (NULL != mqm);
721   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
722               "Suggesting incoming request with accept id %u to listener\n",
723               incoming->suggest_id);
724   cmsg->accept_id = htonl (incoming->suggest_id);
725   cmsg->peer_id = incoming->spec->peer;
726   GNUNET_MQ_send (listener->client_mq, mqm);
727 }
728
729
730 /**
731  * Handle a request for a set operation from another peer.  Checks if we
732  * have a listener waiting for such a request (and in that case initiates
733  * asking the listener about accepting the connection). If no listener
734  * is waiting, we queue the operation request in hope that a listener
735  * shows up soon (before timeout).
736  *
737  * This msg is expected as the first and only msg handled through the
738  * non-operation bound virtual table, acceptance of this operation replaces
739  * our virtual table and subsequent msgs would be routed differently (as
740  * we then know what type of operation this is).
741  *
742  * @param op the operation state
743  * @param mh the received message
744  * @return #GNUNET_OK if the channel should be kept alive,
745  *         #GNUNET_SYSERR to destroy the channel
746  */
747 static int
748 handle_incoming_msg (struct Operation *op,
749                      const struct GNUNET_MessageHeader *mh)
750 {
751   const struct OperationRequestMessage *msg;
752   struct Listener *listener;
753   struct OperationSpecification *spec;
754   const struct GNUNET_MessageHeader *nested_context;
755
756   msg = (const struct OperationRequestMessage *) mh;
757   GNUNET_assert (GNUNET_YES == op->is_incoming);
758   if (GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST != ntohs (mh->type))
759   {
760     GNUNET_break_op (0);
761     return GNUNET_SYSERR;
762   }
763   /* double operation request */
764   if (NULL != op->spec)
765   {
766     GNUNET_break_op (0);
767     return GNUNET_SYSERR;
768   }
769   spec = GNUNET_new (struct OperationSpecification);
770   nested_context = GNUNET_MQ_extract_nested_mh (msg);
771   if ( (NULL != nested_context) &&
772        (ntohs (nested_context->size) > GNUNET_SET_CONTEXT_MESSAGE_MAX_SIZE) )
773   {
774     GNUNET_break_op (0);
775     GNUNET_free (spec);
776     return GNUNET_SYSERR;
777   }
778   /* Make a copy of the nested_context (application-specific context
779      information that is opaque to set) so we can pass it to the
780      listener later on */
781   if (NULL != nested_context)
782     spec->context_msg = GNUNET_copy_message (nested_context);
783   spec->operation = ntohl (msg->operation);
784   spec->app_id = msg->app_id;
785   spec->salt = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
786                                          UINT32_MAX);
787   spec->peer = op->peer;
788   spec->remote_element_count = ntohl (msg->element_count);
789   op->spec = spec;
790
791   listener = listener_get_by_target (ntohl (msg->operation),
792                                      &msg->app_id);
793   if (NULL == listener)
794   {
795     GNUNET_break (NULL != op->timeout_task);
796     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
797                 "No matching listener for incoming request (op %u, app %s), waiting with timeout\n",
798                 ntohl (msg->operation),
799                 GNUNET_h2s (&msg->app_id));
800     return GNUNET_OK;
801   }
802   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
803               "Received P2P operation request (op %u, app %s) for active listener\n",
804               ntohl (msg->operation),
805               GNUNET_h2s (&msg->app_id));
806   incoming_suggest (op, listener);
807   return GNUNET_OK;
808 }
809
810
811 static void
812 execute_add (struct Set *set,
813              const struct GNUNET_MessageHeader *m)
814 {
815   const struct GNUNET_SET_ElementMessage *msg;
816   struct GNUNET_SET_Element el;
817   struct ElementEntry *ee;
818   struct GNUNET_HashCode hash;
819
820   GNUNET_assert (GNUNET_MESSAGE_TYPE_SET_ADD == ntohs (m->type));
821
822   msg = (const struct GNUNET_SET_ElementMessage *) m;
823   el.size = ntohs (m->size) - sizeof *msg;
824   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
825               "Client inserts element of size %u\n",
826               el.size);
827   el.data = &msg[1];
828   GNUNET_CRYPTO_hash (el.data,
829                       el.size,
830                       &hash);
831
832   ee = GNUNET_CONTAINER_multihashmap_get (set->content->elements,
833                                           &hash);
834
835   if (NULL == ee)
836   {
837     ee = GNUNET_malloc (el.size + sizeof *ee);
838     ee->element.size = el.size;
839     memcpy (&ee[1],
840             el.data,
841             el.size);
842     ee->element.data = &ee[1];
843     ee->remote = GNUNET_NO;
844     ee->mutations = NULL;
845     ee->mutations_size = 0;
846     ee->element_hash = hash;
847   }
848   else if (GNUNET_YES == _GSS_is_element_of_set (ee, set))
849   {
850     /* same element inserted twice */
851     return;
852   }
853
854   {
855     struct MutationEvent mut = {
856       .generation = set->current_generation,
857       .added = GNUNET_YES
858     };
859     GNUNET_array_append (ee->mutations, ee->mutations_size, mut);
860   }
861
862   GNUNET_break (GNUNET_YES ==
863                 GNUNET_CONTAINER_multihashmap_put (set->content->elements,
864                                                    &ee->element_hash,
865                                                    ee,
866                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
867   set->vt->add (set->state, ee);
868 }
869
870
871 static void
872 execute_remove (struct Set *set,
873                 const struct GNUNET_MessageHeader *m)
874 {
875   const struct GNUNET_SET_ElementMessage *msg;
876   struct GNUNET_SET_Element el;
877   struct ElementEntry *ee;
878   struct GNUNET_HashCode hash;
879
880   GNUNET_assert (GNUNET_MESSAGE_TYPE_SET_REMOVE == ntohs (m->type));
881
882   msg = (const struct GNUNET_SET_ElementMessage *) m;
883   el.size = ntohs (m->size) - sizeof *msg;
884   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
885               "Client removes element of size %u\n",
886               el.size);
887   el.data = &msg[1];
888   GNUNET_CRYPTO_hash (el.data,
889                       el.size,
890                       &hash);
891   ee = GNUNET_CONTAINER_multihashmap_get (set->content->elements,
892                                           &hash);
893   if (NULL == ee)
894   {
895     /* Client tried to remove non-existing element. */
896     return;
897   }
898   if (GNUNET_NO == _GSS_is_element_of_set (ee, set))
899   {
900     /* Client tried to remove element twice */
901     return;
902   }
903   else
904   {
905     struct MutationEvent mut = {
906       .generation = set->current_generation,
907       .added = GNUNET_NO
908     };
909     GNUNET_array_append (ee->mutations, ee->mutations_size, mut);
910   }
911   set->vt->remove (set->state, ee);
912 }
913
914
915
916 static void
917 execute_mutation (struct Set *set,
918                   const struct GNUNET_MessageHeader *m)
919 {
920   switch (ntohs (m->type))
921   {
922     case GNUNET_MESSAGE_TYPE_SET_ADD:
923       execute_add (set, m);
924       break;
925     case GNUNET_MESSAGE_TYPE_SET_REMOVE:
926       execute_remove (set, m);
927       break;
928     default:
929       GNUNET_break (0);
930   }
931 }
932
933
934
935 /**
936  * Send the next element of a set to the set's client.  The next element is given by
937  * the set's current hashmap iterator.  The set's iterator will be set to NULL if there
938  * are no more elements in the set.  The caller must ensure that the set's iterator is
939  * valid.
940  *
941  * The client will acknowledge each received element with a
942  * #GNUNET_MESSAGE_TYPE_SET_ITER_ACK message.  Our
943  * #handle_client_iter_ack() will then trigger the next transmission.
944  * Note that the #GNUNET_MESSAGE_TYPE_SET_ITER_DONE is not acknowledged.
945  *
946  * @param set set that should send its next element to its client
947  */
948 static void
949 send_client_element (struct Set *set)
950 {
951   int ret;
952   struct ElementEntry *ee;
953   struct GNUNET_MQ_Envelope *ev;
954   struct GNUNET_SET_IterResponseMessage *msg;
955
956   GNUNET_assert (NULL != set->iter);
957
958 again:
959
960   ret = GNUNET_CONTAINER_multihashmap_iterator_next (set->iter,
961                                                      NULL,
962                                                      (const void **) &ee);
963   if (GNUNET_NO == ret)
964   {
965     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
966                 "Iteration on %p done.\n",
967                 (void *) set);
968     ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SET_ITER_DONE);
969     GNUNET_CONTAINER_multihashmap_iterator_destroy (set->iter);
970     set->iter = NULL;
971     set->iteration_id++;
972     
973     GNUNET_assert (set->content->iterator_count > 0);
974     set->content->iterator_count -= 1;
975
976     if (0 == set->content->iterator_count)
977     {
978       while (NULL != set->content->pending_mutations_head)
979       {
980         struct PendingMutation *pm;
981
982         pm = set->content->pending_mutations_head;
983         GNUNET_CONTAINER_DLL_remove (set->content->pending_mutations_head,
984                                      set->content->pending_mutations_tail,
985                                      pm);
986         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
987                     "Executing pending mutation on %p.\n",
988                     (void *) pm->set);
989         execute_mutation (pm->set, pm->mutation_message);
990         GNUNET_free (pm->mutation_message);
991         GNUNET_free (pm);
992       }
993     }
994
995   }
996   else
997   {
998     GNUNET_assert (NULL != ee);
999
1000     if (GNUNET_NO == is_element_of_iteration (ee, set))
1001       goto again;
1002
1003     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1004                 "Sending iteration element on %p.\n",
1005                 (void *) set);
1006     ev = GNUNET_MQ_msg_extra (msg,
1007                               ee->element.size,
1008                               GNUNET_MESSAGE_TYPE_SET_ITER_ELEMENT);
1009     memcpy (&msg[1],
1010             ee->element.data,
1011             ee->element.size);
1012     msg->element_type = ee->element.element_type;
1013     msg->iteration_id = htons (set->iteration_id);
1014   }
1015   GNUNET_MQ_send (set->client_mq, ev);
1016 }
1017
1018
1019 /**
1020  * Called when a client wants to iterate the elements of a set.
1021  * Checks if we have a set associated with the client and if we
1022  * can right now start an iteration. If all checks out, starts
1023  * sending the elements of the set to the client.
1024  *
1025  * @param cls unused
1026  * @param client client that sent the message
1027  * @param m message sent by the client
1028  */
1029 static void
1030 handle_client_iterate (void *cls,
1031                        struct GNUNET_SERVER_Client *client,
1032                        const struct GNUNET_MessageHeader *m)
1033 {
1034   struct Set *set;
1035
1036   set = set_get (client);
1037   if (NULL == set)
1038   {
1039     /* attempt to iterate over a non existing set */
1040     GNUNET_break (0);
1041     GNUNET_SERVER_client_disconnect (client);
1042     return;
1043   }
1044   if (NULL != set->iter)
1045   {
1046     /* Only one concurrent iterate-action allowed per set */
1047     GNUNET_break (0);
1048     GNUNET_SERVER_client_disconnect (client);
1049     return;
1050   }
1051   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1052               "Iterating set %p in gen %u with %u content elements\n",
1053               (void *) set,
1054               set->current_generation,
1055               GNUNET_CONTAINER_multihashmap_size (set->content->elements));
1056   GNUNET_SERVER_receive_done (client,
1057                               GNUNET_OK);
1058   set->content->iterator_count += 1;
1059   set->iter = GNUNET_CONTAINER_multihashmap_iterator_create (set->content->elements);
1060   set->iter_generation = set->current_generation;
1061   send_client_element (set);
1062 }
1063
1064
1065 /**
1066  * Called when a client wants to create a new set.  This is typically
1067  * the first request from a client, and includes the type of set
1068  * operation to be performed.
1069  *
1070  * @param cls unused
1071  * @param client client that sent the message
1072  * @param m message sent by the client
1073  */
1074 static void
1075 handle_client_create_set (void *cls,
1076                           struct GNUNET_SERVER_Client *client,
1077                           const struct GNUNET_MessageHeader *m)
1078 {
1079   const struct GNUNET_SET_CreateMessage *msg;
1080   struct Set *set;
1081
1082   msg = (const struct GNUNET_SET_CreateMessage *) m;
1083   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1084               "Client created new set (operation %u)\n",
1085               ntohl (msg->operation));
1086   if (NULL != set_get (client))
1087   {
1088     /* There can only be one set per client */
1089     GNUNET_break (0);
1090     GNUNET_SERVER_client_disconnect (client);
1091     return;
1092   }
1093   set = GNUNET_new (struct Set);
1094   switch (ntohl (msg->operation))
1095   {
1096   case GNUNET_SET_OPERATION_INTERSECTION:
1097     set->vt = _GSS_intersection_vt ();
1098     break;
1099   case GNUNET_SET_OPERATION_UNION:
1100     set->vt = _GSS_union_vt ();
1101     break;
1102   default:
1103     GNUNET_free (set);
1104     GNUNET_break (0);
1105     GNUNET_SERVER_client_disconnect (client);
1106     return;
1107   }
1108   set->operation = ntohl (msg->operation);
1109   set->state = set->vt->create ();
1110   set->content = GNUNET_new (struct SetContent);
1111   set->content->refcount = 1;
1112   set->content->elements = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
1113   set->client = client;
1114   set->client_mq = GNUNET_MQ_queue_for_server_client (client);
1115   GNUNET_CONTAINER_DLL_insert (sets_head,
1116                                sets_tail,
1117                                set);
1118   GNUNET_SERVER_receive_done (client,
1119                               GNUNET_OK);
1120 }
1121
1122
1123 /**
1124  * Called when a client wants to create a new listener.
1125  *
1126  * @param cls unused
1127  * @param client client that sent the message
1128  * @param m message sent by the client
1129  */
1130 static void
1131 handle_client_listen (void *cls,
1132                       struct GNUNET_SERVER_Client *client,
1133                       const struct GNUNET_MessageHeader *m)
1134 {
1135   const struct GNUNET_SET_ListenMessage *msg;
1136   struct Listener *listener;
1137   struct Operation *op;
1138
1139   msg = (const struct GNUNET_SET_ListenMessage *) m;
1140   if (NULL != listener_get (client))
1141   {
1142     /* max. one active listener per client! */
1143     GNUNET_break (0);
1144     GNUNET_SERVER_client_disconnect (client);
1145     return;
1146   }
1147   listener = GNUNET_new (struct Listener);
1148   listener->client = client;
1149   listener->client_mq = GNUNET_MQ_queue_for_server_client (client);
1150   listener->app_id = msg->app_id;
1151   listener->operation = ntohl (msg->operation);
1152   GNUNET_CONTAINER_DLL_insert_tail (listeners_head,
1153                                     listeners_tail,
1154                                     listener);
1155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1156               "New listener created (op %u, app %s)\n",
1157               listener->operation,
1158               GNUNET_h2s (&listener->app_id));
1159
1160   /* check for existing incoming requests the listener might be interested in */
1161   for (op = incoming_head; NULL != op; op = op->next)
1162   {
1163     if (NULL == op->spec)
1164       continue; /* no details available yet */
1165     if (0 != op->suggest_id)
1166       continue; /* this one has been already suggested to a listener */
1167     if (listener->operation != op->spec->operation)
1168       continue; /* incompatible operation */
1169     if (0 != GNUNET_CRYPTO_hash_cmp (&listener->app_id,
1170                                      &op->spec->app_id))
1171       continue; /* incompatible appliation */
1172     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1173                 "Found matching existing request\n");
1174     incoming_suggest (op,
1175                       listener);
1176   }
1177   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1178 }
1179
1180
1181 /**
1182  * Called when the listening client rejects an operation
1183  * request by another peer.
1184  *
1185  * @param cls unused
1186  * @param client client that sent the message
1187  * @param m message sent by the client
1188  */
1189 static void
1190 handle_client_reject (void *cls,
1191                       struct GNUNET_SERVER_Client *client,
1192                       const struct GNUNET_MessageHeader *m)
1193 {
1194   struct Operation *incoming;
1195   const struct GNUNET_SET_RejectMessage *msg;
1196
1197   msg = (const struct GNUNET_SET_RejectMessage *) m;
1198   incoming = get_incoming (ntohl (msg->accept_reject_id));
1199   if (NULL == incoming)
1200   {
1201     /* no matching incoming operation for this reject */
1202     GNUNET_break (0);
1203     GNUNET_SERVER_receive_done (client,
1204                                 GNUNET_SYSERR);
1205     return;
1206   }
1207   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1208               "Peer request (op %u, app %s) rejected by client\n",
1209               incoming->spec->operation,
1210               GNUNET_h2s (&incoming->spec->app_id));
1211   GNUNET_CADET_channel_destroy (incoming->channel);
1212   GNUNET_SERVER_receive_done (client,
1213                               GNUNET_OK);
1214 }
1215
1216
1217
1218 /**
1219  * Called when a client wants to add or remove an element to a set it inhabits.
1220  *
1221  * @param cls unused
1222  * @param client client that sent the message
1223  * @param m message sent by the client
1224  */
1225 static void
1226 handle_client_mutation (void *cls,
1227                         struct GNUNET_SERVER_Client *client,
1228                         const struct GNUNET_MessageHeader *m)
1229 {
1230   struct Set *set;
1231
1232   set = set_get (client);
1233   if (NULL == set)
1234   {
1235     /* client without a set requested an operation */
1236     GNUNET_break (0);
1237     GNUNET_SERVER_client_disconnect (client);
1238     return;
1239   }
1240
1241   GNUNET_SERVER_receive_done (client,
1242                               GNUNET_OK);
1243
1244   if (0 != set->content->iterator_count)
1245   {
1246     struct PendingMutation *pm;
1247
1248     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1249                 "Scheduling mutation on set\n");
1250
1251     pm = GNUNET_new (struct PendingMutation);
1252     pm->mutation_message = GNUNET_copy_message (m);
1253     pm->set = set;
1254     GNUNET_CONTAINER_DLL_insert (set->content->pending_mutations_head,
1255                                  set->content->pending_mutations_tail,
1256                                  pm);
1257     return;
1258   }
1259
1260   execute_mutation (set, m);
1261 }
1262
1263
1264 /**
1265  * Advance the current generation of a set,
1266  * adding exclusion ranges if necessary.
1267  *
1268  * @param set the set where we want to advance the generation
1269  */
1270 static void
1271 advance_generation (struct Set *set)
1272 {
1273   struct GenerationRange r;
1274
1275   if (set->current_generation == set->content->latest_generation)
1276   {
1277     set->content->latest_generation += 1;
1278     set->current_generation += 1;
1279     return;
1280   }
1281
1282   GNUNET_assert (set->current_generation < set->content->latest_generation);
1283
1284   r.start = set->current_generation + 1;
1285   r.end = set->content->latest_generation + 1;
1286
1287   set->content->latest_generation = r.end;
1288   set->current_generation = r.end;
1289
1290   GNUNET_array_append (set->excluded_generations,
1291                        set->excluded_generations_size,
1292                        r);
1293 }
1294
1295 /**
1296  * Called when a client wants to initiate a set operation with another
1297  * peer.  Initiates the CADET connection to the listener and sends the
1298  * request.
1299  *
1300  * @param cls unused
1301  * @param client client that sent the message
1302  * @param m message sent by the client
1303  */
1304 static void
1305 handle_client_evaluate (void *cls,
1306                         struct GNUNET_SERVER_Client *client,
1307                         const struct GNUNET_MessageHeader *m)
1308 {
1309   struct Set *set;
1310   const struct GNUNET_SET_EvaluateMessage *msg;
1311   struct OperationSpecification *spec;
1312   struct Operation *op;
1313   const struct GNUNET_MessageHeader *context;
1314
1315   set = set_get (client);
1316   if (NULL == set)
1317   {
1318     GNUNET_break (0);
1319     GNUNET_SERVER_client_disconnect (client);
1320     return;
1321   }
1322   msg = (const struct GNUNET_SET_EvaluateMessage *) m;
1323   spec = GNUNET_new (struct OperationSpecification);
1324   spec->operation = set->operation;
1325   spec->app_id = msg->app_id;
1326   spec->salt = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1327                                          UINT32_MAX);
1328   spec->peer = msg->target_peer;
1329   spec->set = set;
1330   spec->result_mode = ntohl (msg->result_mode);
1331   spec->client_request_id = ntohl (msg->request_id);
1332   context = GNUNET_MQ_extract_nested_mh (msg);
1333   op = GNUNET_new (struct Operation);
1334   op->spec = spec;
1335
1336   // Advance generation values, so that
1337   // mutations won't interfer with the running operation.
1338   op->generation_created = set->current_generation;
1339   advance_generation (set);
1340
1341   op->vt = set->vt;
1342   GNUNET_CONTAINER_DLL_insert (set->ops_head,
1343                                set->ops_tail,
1344                                op);
1345   op->channel = GNUNET_CADET_channel_create (cadet,
1346                                              op,
1347                                              &msg->target_peer,
1348                                              GNUNET_APPLICATION_TYPE_SET,
1349                                              GNUNET_CADET_OPTION_RELIABLE);
1350   op->mq = GNUNET_CADET_mq_create (op->channel);
1351   set->vt->evaluate (op,
1352                      context);
1353   GNUNET_SERVER_receive_done (client,
1354                               GNUNET_OK);
1355 }
1356
1357
1358 /**
1359  * Handle an ack from a client, and send the next element. Note
1360  * that we only expect acks for set elements, not after the
1361  * #GNUNET_MESSAGE_TYPE_SET_ITER_DONE message.
1362  *
1363  * @param cls unused
1364  * @param client the client
1365  * @param m the message
1366  */
1367 static void
1368 handle_client_iter_ack (void *cls,
1369                         struct GNUNET_SERVER_Client *client,
1370                         const struct GNUNET_MessageHeader *m)
1371 {
1372   const struct GNUNET_SET_IterAckMessage *ack;
1373   struct Set *set;
1374
1375   set = set_get (client);
1376   if (NULL == set)
1377   {
1378     /* client without a set acknowledged receiving a value */
1379     GNUNET_break (0);
1380     GNUNET_SERVER_client_disconnect (client);
1381     return;
1382   }
1383   if (NULL == set->iter)
1384   {
1385     /* client sent an ack, but we were not expecting one (as
1386        set iteration has finished) */
1387     GNUNET_break (0);
1388     GNUNET_SERVER_client_disconnect (client);
1389     return;
1390   }
1391   ack = (const struct GNUNET_SET_IterAckMessage *) m;
1392   GNUNET_SERVER_receive_done (client,
1393                               GNUNET_OK);
1394   if (ntohl (ack->send_more))
1395   {
1396     send_client_element (set);
1397   }
1398   else
1399   {
1400     GNUNET_CONTAINER_multihashmap_iterator_destroy (set->iter);
1401     set->iter = NULL;
1402     set->iteration_id++;
1403   }
1404 }
1405
1406
1407 /**
1408  * Handle a request from the client to
1409  * copy a set.
1410  *
1411  * @param cls unused
1412  * @param client the client
1413  * @param mh the message
1414  */
1415 static void
1416 handle_client_copy_lazy_prepare (void *cls,
1417                                  struct GNUNET_SERVER_Client *client,
1418                                  const struct GNUNET_MessageHeader *mh)
1419 {
1420   struct Set *set;
1421   struct LazyCopyRequest *cr;
1422   struct GNUNET_MQ_Envelope *ev;
1423   struct GNUNET_SET_CopyLazyResponseMessage *resp_msg;
1424
1425   set = set_get (client);
1426   if (NULL == set)
1427   {
1428     /* client without a set requested an operation */
1429     GNUNET_break (0);
1430     GNUNET_SERVER_client_disconnect (client);
1431     return;
1432   }
1433
1434   cr = GNUNET_new (struct LazyCopyRequest);
1435
1436   cr->cookie = lazy_copy_cookie;
1437   lazy_copy_cookie += 1;
1438   cr->source_set = set;
1439
1440   GNUNET_CONTAINER_DLL_insert (lazy_copy_head,
1441                                lazy_copy_tail,
1442                                cr);
1443
1444
1445   ev = GNUNET_MQ_msg (resp_msg,
1446                       GNUNET_MESSAGE_TYPE_SET_COPY_LAZY_RESPONSE);
1447   resp_msg->cookie = cr->cookie;
1448   GNUNET_MQ_send (set->client_mq, ev);
1449
1450
1451   GNUNET_SERVER_receive_done (client,
1452                               GNUNET_OK);
1453
1454   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1455               "Client requested lazy copy\n");
1456 }
1457
1458
1459 /**
1460  * Handle a request from the client to
1461  * connect to a copy of a set.
1462  *
1463  * @param cls unused
1464  * @param client the client
1465  * @param mh the message
1466  */
1467 static void
1468 handle_client_copy_lazy_connect (void *cls,
1469                                  struct GNUNET_SERVER_Client *client,
1470                                  const struct GNUNET_MessageHeader *mh)
1471 {
1472   struct LazyCopyRequest *cr;
1473   const struct GNUNET_SET_CopyLazyConnectMessage *msg =
1474       (const struct GNUNET_SET_CopyLazyConnectMessage *) mh;
1475   struct Set *set;
1476   int found;
1477
1478   if (NULL != set_get (client))
1479   {
1480     /* There can only be one set per client */
1481     GNUNET_break (0);
1482     GNUNET_SERVER_client_disconnect (client);
1483     return;
1484   }
1485
1486   found = GNUNET_NO;
1487
1488   for (cr = lazy_copy_head; NULL != cr; cr = cr->next)
1489   {
1490     if (cr->cookie == msg->cookie)
1491     {
1492       found = GNUNET_YES;
1493       break;
1494     } 
1495   }
1496
1497   if (GNUNET_NO == found)
1498   {
1499     /* client asked for copy with cookie we don't know */
1500     GNUNET_break (0);
1501     GNUNET_SERVER_client_disconnect (client);
1502     return;
1503   }
1504
1505   GNUNET_CONTAINER_DLL_remove (lazy_copy_head,
1506                                lazy_copy_tail,
1507                                cr);
1508
1509   set = GNUNET_new (struct Set);
1510
1511   switch (cr->source_set->operation)
1512   {
1513   case GNUNET_SET_OPERATION_INTERSECTION:
1514     set->vt = _GSS_intersection_vt ();
1515     break;
1516   case GNUNET_SET_OPERATION_UNION:
1517     set->vt = _GSS_union_vt ();
1518     break;
1519   default:
1520     GNUNET_assert (0);
1521     return;
1522   }
1523
1524   if (NULL == set->vt->copy_state) {
1525     /* Lazy copy not supported for this set operation */
1526     GNUNET_break (0);
1527     GNUNET_free (set);
1528     GNUNET_free (cr);
1529     GNUNET_SERVER_client_disconnect (client);
1530     return;
1531   }
1532
1533   set->operation = cr->source_set->operation;
1534   set->state = set->vt->copy_state (cr->source_set);
1535   set->content = cr->source_set->content;
1536   set->content->refcount += 1;
1537
1538   set->current_generation = cr->source_set->current_generation;
1539   set->excluded_generations_size = cr->source_set->excluded_generations_size;
1540   set->excluded_generations = GNUNET_memdup (cr->source_set->excluded_generations,
1541                                              set->excluded_generations_size * sizeof (struct GenerationRange));
1542
1543   /* Advance the generation of the new set, so that mutations to the
1544      of the cloned set and the source set are independent. */
1545   advance_generation (set);
1546
1547
1548   set->client = client;
1549   set->client_mq = GNUNET_MQ_queue_for_server_client (client);
1550   GNUNET_CONTAINER_DLL_insert (sets_head,
1551                                sets_tail,
1552                                set);
1553
1554   GNUNET_free (cr);
1555
1556   GNUNET_SERVER_receive_done (client,
1557                               GNUNET_OK);
1558
1559   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1560               "Client connected to lazy set\n");
1561 }
1562
1563
1564 /**
1565  * Handle a request from the client to
1566  * cancel a running set operation.
1567  *
1568  * @param cls unused
1569  * @param client the client
1570  * @param mh the message
1571  */
1572 static void
1573 handle_client_cancel (void *cls,
1574                       struct GNUNET_SERVER_Client *client,
1575                       const struct GNUNET_MessageHeader *mh)
1576 {
1577   const struct GNUNET_SET_CancelMessage *msg =
1578       (const struct GNUNET_SET_CancelMessage *) mh;
1579   struct Set *set;
1580   struct Operation *op;
1581   int found;
1582
1583   set = set_get (client);
1584   if (NULL == set)
1585   {
1586     /* client without a set requested an operation */
1587     GNUNET_break (0);
1588     GNUNET_SERVER_client_disconnect (client);
1589     return;
1590   }
1591   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1592               "Client requested cancel for op %u\n",
1593               ntohl (msg->request_id));
1594   found = GNUNET_NO;
1595   for (op = set->ops_head; NULL != op; op = op->next)
1596   {
1597     if (op->spec->client_request_id == ntohl (msg->request_id))
1598     {
1599       found = GNUNET_YES;
1600       break;
1601     }
1602   }
1603   if (GNUNET_NO == found)
1604   {
1605     /* It may happen that the operation was already destroyed due to
1606      * the other peer disconnecting.  The client may not know about this
1607      * yet and try to cancel the (just barely non-existent) operation.
1608      * So this is not a hard error.
1609      */
1610     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1611                 "Client canceled non-existent op\n");
1612   }
1613   else
1614   {
1615     _GSS_operation_destroy (op,
1616                             GNUNET_YES);
1617   }
1618   GNUNET_SERVER_receive_done (client,
1619                               GNUNET_OK);
1620 }
1621
1622
1623 /**
1624  * Handle a request from the client to accept a set operation that
1625  * came from a remote peer.  We forward the accept to the associated
1626  * operation for handling
1627  *
1628  * @param cls unused
1629  * @param client the client
1630  * @param mh the message
1631  */
1632 static void
1633 handle_client_accept (void *cls,
1634                       struct GNUNET_SERVER_Client *client,
1635                       const struct GNUNET_MessageHeader *mh)
1636 {
1637   struct Set *set;
1638   const struct GNUNET_SET_AcceptMessage *msg;
1639   struct Operation *op;
1640   struct GNUNET_SET_ResultMessage *result_message;
1641   struct GNUNET_MQ_Envelope *ev;
1642
1643   msg = (const struct GNUNET_SET_AcceptMessage *) mh;
1644   set = set_get (client);
1645   if (NULL == set)
1646   {
1647     /* client without a set requested to accept */
1648     GNUNET_break (0);
1649     GNUNET_SERVER_client_disconnect (client);
1650     return;
1651   }
1652   op = get_incoming (ntohl (msg->accept_reject_id));
1653   if (NULL == op)
1654   {
1655     /* It is not an error if the set op does not exist -- it may
1656      * have been destroyed when the partner peer disconnected. */
1657     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1658                 "Client accepted request that is no longer active\n");
1659     ev = GNUNET_MQ_msg (result_message,
1660                         GNUNET_MESSAGE_TYPE_SET_RESULT);
1661     result_message->request_id = msg->request_id;
1662     result_message->element_type = 0;
1663     result_message->result_status = htons (GNUNET_SET_STATUS_FAILURE);
1664     GNUNET_MQ_send (set->client_mq, ev);
1665     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1666     return;
1667   }
1668
1669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1670               "Client accepting request %u\n",
1671               ntohl (msg->accept_reject_id));
1672   GNUNET_assert (GNUNET_YES == op->is_incoming);
1673   op->is_incoming = GNUNET_NO;
1674   GNUNET_CONTAINER_DLL_remove (incoming_head,
1675                                incoming_tail,
1676                                op);
1677   op->spec->set = set;
1678   GNUNET_CONTAINER_DLL_insert (set->ops_head,
1679                                set->ops_tail,
1680                                op);
1681   op->spec->client_request_id = ntohl (msg->request_id);
1682   op->spec->result_mode = ntohl (msg->result_mode);
1683
1684   // Advance generation values, so that
1685   // mutations won't interfer with the running operation.
1686   op->generation_created = set->current_generation;
1687   advance_generation (set);
1688
1689   op->vt = set->vt;
1690   op->vt->accept (op);
1691   GNUNET_SERVER_receive_done (client,
1692                               GNUNET_OK);
1693 }
1694
1695
1696 /**
1697  * Called to clean up, after a shutdown has been requested.
1698  *
1699  * @param cls closure
1700  * @param tc context information (why was this task triggered now)
1701  */
1702 static void
1703 shutdown_task (void *cls,
1704                const struct GNUNET_SCHEDULER_TaskContext *tc)
1705 {
1706   while (NULL != incoming_head)
1707     incoming_destroy (incoming_head);
1708   while (NULL != listeners_head)
1709     listener_destroy (listeners_head);
1710   while (NULL != sets_head)
1711     set_destroy (sets_head);
1712
1713   /* it's important to destroy cadet at the end, as all channels
1714    * must be destroyed before the cadet handle! */
1715   if (NULL != cadet)
1716   {
1717     GNUNET_CADET_disconnect (cadet);
1718     cadet = NULL;
1719   }
1720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1721               "handled shutdown request\n");
1722 }
1723
1724
1725 /**
1726  * Timeout happens iff:
1727  *  - we suggested an operation to our listener,
1728  *    but did not receive a response in time
1729  *  - we got the channel from a peer but no #GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST
1730  *  - shutdown (obviously)
1731  *
1732  * @param cls channel context
1733  * @param tc context information (why was this task triggered now)
1734  */
1735 static void
1736 incoming_timeout_cb (void *cls,
1737                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1738 {
1739   struct Operation *incoming = cls;
1740
1741   incoming->timeout_task = NULL;
1742   GNUNET_assert (GNUNET_YES == incoming->is_incoming);
1743   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1744     return;
1745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1746               "Remote peer's incoming request timed out\n");
1747   incoming_destroy (incoming);
1748 }
1749
1750
1751 /**
1752  * Terminates an incoming operation in case we have not yet received an
1753  * operation request. Called by the channel destruction handler.
1754  *
1755  * @param op the channel context
1756  */
1757 static void
1758 handle_incoming_disconnect (struct Operation *op)
1759 {
1760   GNUNET_assert (GNUNET_YES == op->is_incoming);
1761   /* channel is already dead, incoming_destroy must not
1762    * destroy it ... */
1763   op->channel = NULL;
1764   incoming_destroy (op);
1765   op->vt = NULL;
1766 }
1767
1768
1769 /**
1770  * Method called whenever another peer has added us to a channel the
1771  * other peer initiated.  Only called (once) upon reception of data
1772  * with a message type which was subscribed to in
1773  * GNUNET_CADET_connect().
1774  *
1775  * The channel context represents the operation itself and gets added to a DLL,
1776  * from where it gets looked up when our local listener client responds
1777  * to a proposed/suggested operation or connects and associates with this operation.
1778  *
1779  * @param cls closure
1780  * @param channel new handle to the channel
1781  * @param initiator peer that started the channel
1782  * @param port Port this channel is for.
1783  * @param options Unused.
1784  * @return initial channel context for the channel
1785  *         returns NULL on error
1786  */
1787 static void *
1788 channel_new_cb (void *cls,
1789                 struct GNUNET_CADET_Channel *channel,
1790                 const struct GNUNET_PeerIdentity *initiator,
1791                 uint32_t port,
1792                 enum GNUNET_CADET_ChannelOption options)
1793 {
1794   static const struct SetVT incoming_vt = {
1795     .msg_handler = &handle_incoming_msg,
1796     .peer_disconnect = &handle_incoming_disconnect
1797   };
1798   struct Operation *incoming;
1799
1800   if (GNUNET_APPLICATION_TYPE_SET != port)
1801   {
1802     GNUNET_break (0);
1803     GNUNET_CADET_channel_destroy (channel);
1804     return NULL;
1805   }
1806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1807               "New incoming channel\n");
1808   incoming = GNUNET_new (struct Operation);
1809   incoming->is_incoming = GNUNET_YES;
1810   incoming->peer = *initiator;
1811   incoming->channel = channel;
1812   incoming->mq = GNUNET_CADET_mq_create (incoming->channel);
1813   incoming->vt = &incoming_vt;
1814   incoming->timeout_task
1815     = GNUNET_SCHEDULER_add_delayed (INCOMING_CHANNEL_TIMEOUT,
1816                                     &incoming_timeout_cb,
1817                                     incoming);
1818   GNUNET_CONTAINER_DLL_insert_tail (incoming_head,
1819                                     incoming_tail,
1820                                     incoming);
1821   return incoming;
1822 }
1823
1824
1825 /**
1826  * Function called whenever a channel is destroyed.  Should clean up
1827  * any associated state.  It must NOT call
1828  * GNUNET_CADET_channel_destroy() on the channel.
1829  *
1830  * The peer_disconnect function is part of a a virtual table set initially either
1831  * when a peer creates a new channel with us (#channel_new_cb()), or once we create
1832  * a new channel ourselves (evaluate).
1833  *
1834  * Once we know the exact type of operation (union/intersection), the vt is
1835  * replaced with an operation specific instance (_GSS_[op]_vt).
1836  *
1837  * @param cls closure (set from GNUNET_CADET_connect())
1838  * @param channel connection to the other end (henceforth invalid)
1839  * @param channel_ctx place where local state associated
1840  *                   with the channel is stored
1841  */
1842 static void
1843 channel_end_cb (void *cls,
1844                 const struct GNUNET_CADET_Channel *channel,
1845                 void *channel_ctx)
1846 {
1847   struct Operation *op = channel_ctx;
1848
1849   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1850               "channel_end_cb called\n");
1851   op->channel = NULL;
1852   op->keep++;
1853   /* the vt can be null if a client already requested canceling op. */
1854   if (NULL != op->vt)
1855   {
1856     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1857                 "calling peer disconnect due to channel end\n");
1858     op->vt->peer_disconnect (op);
1859   }
1860   op->keep--;
1861   if (0 == op->keep)
1862   {
1863     /* cadet will never call us with the context again! */
1864     GNUNET_free (op);
1865   }
1866   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1867               "channel_end_cb finished\n");
1868 }
1869
1870
1871 /**
1872  * Functions with this signature are called whenever a message is
1873  * received via a cadet channel.
1874  *
1875  * The msg_handler is a virtual table set in initially either when a peer
1876  * creates a new channel with us (channel_new_cb), or once we create a new channel
1877  * ourselves (evaluate).
1878  *
1879  * Once we know the exact type of operation (union/intersection), the vt is
1880  * replaced with an operation specific instance (_GSS_[op]_vt).
1881  *
1882  * @param cls Closure (set from GNUNET_CADET_connect()).
1883  * @param channel Connection to the other end.
1884  * @param channel_ctx Place to store local state associated with the channel.
1885  * @param message The actual message.
1886  * @return #GNUNET_OK to keep the channel open,
1887  *         #GNUNET_SYSERR to close it (signal serious error).
1888  */
1889 static int
1890 dispatch_p2p_message (void *cls,
1891                       struct GNUNET_CADET_Channel *channel,
1892                       void **channel_ctx,
1893                       const struct GNUNET_MessageHeader *message)
1894 {
1895   struct Operation *op = *channel_ctx;
1896   int ret;
1897
1898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1899               "Dispatching cadet message (type: %u)\n",
1900               ntohs (message->type));
1901   /* do this before the handler, as the handler might kill the channel */
1902   GNUNET_CADET_receive_done (channel);
1903   if (NULL != op->vt)
1904     ret = op->vt->msg_handler (op,
1905                                message);
1906   else
1907     ret = GNUNET_SYSERR;
1908   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1909               "Handled cadet message (type: %u)\n",
1910               ntohs (message->type));
1911   return ret;
1912 }
1913
1914
1915 /**
1916  * Function called by the service's run
1917  * method to run service-specific setup code.
1918  *
1919  * @param cls closure
1920  * @param server the initialized server
1921  * @param cfg configuration to use
1922  */
1923 static void
1924 run (void *cls,
1925      struct GNUNET_SERVER_Handle *server,
1926      const struct GNUNET_CONFIGURATION_Handle *cfg)
1927 {
1928   static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
1929     { &handle_client_accept, NULL,
1930       GNUNET_MESSAGE_TYPE_SET_ACCEPT,
1931       sizeof (struct GNUNET_SET_AcceptMessage)},
1932     { &handle_client_iter_ack, NULL,
1933       GNUNET_MESSAGE_TYPE_SET_ITER_ACK,
1934       sizeof (struct GNUNET_SET_IterAckMessage) },
1935     { &handle_client_mutation, NULL,
1936       GNUNET_MESSAGE_TYPE_SET_ADD,
1937       0},
1938     { &handle_client_create_set, NULL,
1939       GNUNET_MESSAGE_TYPE_SET_CREATE,
1940       sizeof (struct GNUNET_SET_CreateMessage)},
1941     { &handle_client_iterate, NULL,
1942       GNUNET_MESSAGE_TYPE_SET_ITER_REQUEST,
1943       sizeof (struct GNUNET_MessageHeader)},
1944     { &handle_client_evaluate, NULL,
1945       GNUNET_MESSAGE_TYPE_SET_EVALUATE,
1946       0},
1947     { &handle_client_listen, NULL,
1948       GNUNET_MESSAGE_TYPE_SET_LISTEN,
1949       sizeof (struct GNUNET_SET_ListenMessage)},
1950     { &handle_client_reject, NULL,
1951       GNUNET_MESSAGE_TYPE_SET_REJECT,
1952       sizeof (struct GNUNET_SET_RejectMessage)},
1953     { &handle_client_mutation, NULL,
1954       GNUNET_MESSAGE_TYPE_SET_REMOVE,
1955       0},
1956     { &handle_client_cancel, NULL,
1957       GNUNET_MESSAGE_TYPE_SET_CANCEL,
1958       sizeof (struct GNUNET_SET_CancelMessage)},
1959     { &handle_client_copy_lazy_prepare, NULL,
1960       GNUNET_MESSAGE_TYPE_SET_COPY_LAZY_PREPARE,
1961       sizeof (struct GNUNET_MessageHeader)},
1962     { &handle_client_copy_lazy_connect, NULL,
1963       GNUNET_MESSAGE_TYPE_SET_COPY_LAZY_CONNECT,
1964       sizeof (struct GNUNET_SET_CopyLazyConnectMessage)},
1965     { NULL, NULL, 0, 0}
1966   };
1967   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1968     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST, 0},
1969     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_IBF, 0},
1970     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS, 0},
1971     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_OFFER, 0},
1972     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_INQUIRY, 0},
1973     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DEMAND, 0},
1974     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENT_REQUESTS, 0},
1975     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DONE, 0},
1976     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_SE, 0},
1977     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_ELEMENT_INFO, 0},
1978     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_BF, 0},
1979     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_DONE, 0},
1980     {NULL, 0, 0}
1981   };
1982   static const uint32_t cadet_ports[] = {GNUNET_APPLICATION_TYPE_SET, 0};
1983
1984   configuration = cfg;
1985   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1986                                 &shutdown_task, NULL);
1987   GNUNET_SERVER_disconnect_notify (server,
1988                                    &handle_client_disconnect, NULL);
1989   GNUNET_SERVER_add_handlers (server,
1990                               server_handlers);
1991   cadet = GNUNET_CADET_connect (cfg, NULL,
1992                                 &channel_new_cb,
1993                                 &channel_end_cb,
1994                                 cadet_handlers,
1995                                 cadet_ports);
1996   if (NULL == cadet)
1997   {
1998     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1999                 _("Could not connect to cadet service\n"));
2000     return;
2001   }
2002 }
2003
2004
2005 /**
2006  * The main function for the set service.
2007  *
2008  * @param argc number of arguments from the command line
2009  * @param argv command line arguments
2010  * @return 0 ok, 1 on error
2011  */
2012 int
2013 main (int argc,
2014       char *const *argv)
2015 {
2016   int ret;
2017
2018   ret = GNUNET_SERVICE_run (argc, argv, "set",
2019                             GNUNET_SERVICE_OPTION_NONE,
2020                             &run, NULL);
2021   return (GNUNET_OK == ret) ? 0 : 1;
2022 }
2023
2024 /* end of gnunet-service-set.c */