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